无法创建类的多个实例

时间:2014-10-23 02:00:39

标签: php object

我正在编写一个PHP应用程序,我正在尝试一个奇怪的bug。我有一个名为权限的类,表示为:

//Permissions class
class Permission {
    //Permission name
    protected $permission_name = "";

    //Constructor method
    function __construct($name) {
        //Get global reference for variables used here
        global $permission_name;

        //Save the permission name
        $permission_name = $name;

        echo("<br>" . $name . "<br>");
    }

    //Compare permissions
    function compare($permission) {
        //Get global reference for variables used here
        global $permission_name;

        //Break down the permissions into arrays
        $permission_a_data = explode(".", $permission_name);
        $permission_b_data = explode(".", $permission);

        //Iterate through the permission values
        foreach($permission_a_data as $index=>$perm) {
            //Check for a wildcard permission
            if($perm == "*") {
                //User has wildcard permission
                return true;
            }
            //Check if permission has ended
            if(!isSet($permission_b_data[$index])) {
                //User does not have adequate permission
                return false;
            }
            //Check if permission is different
            if($permission_b_data[$index] != $perm) {
                //Permissions differ
                return false;
            }
        }

        //If application reaches this point, permissions are identical
        return true;
    }

    //Get the name
    function get_name() {
        //Get global reference for objects used here
        global $permission_name;
        //Return the name
        return $permission_name;
    }
}

我在应用程序的其他地方有一些代码,如:

$permission1 = new Permission("This.is.a.test");
$permission2 = new Permission("test.a.is.This");
echo("<br>DEBUG:<br>");
echo($permission1->get_name() . "<br>");
echo($permission2->get_name() . "<br>");

然而第二段代码总是打印出来:

DEBUG:
test.a.is.This
test.a.is.This

我不知道为什么会这样,并且非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

每次拨打$permission_name个实例时都会覆盖new,因为function __construct $permission_nameglobal->get_name()global返回相同的{{1}}变量。

答案 1 :(得分:0)

从班级中删除global $permission_name行。

您可以使用$this来引用该班级的当前实例。因此,您可以使用$this->permission_name访问当前instance.some的$permission_name,例如,

class Permission {
    //Permission name
    protected $permission_name = "";

    //Constructor method
    function __construct($name) {

        $this->permission_name = $name;

    }

    function compare($permission) {

        //Break down the permissions into arrays
        $permission_a_data = explode(".", $this->permission_name);

        //....
    }

    function get_name() {

        //Return the name
        return $this->permission_name;
   }

}
相关问题