2014-10-23 5 views
0

이상한 버그를 경험하고있는 PHP 응용 프로그램을 작성하고 있습니다. 나는 같은 표현되는 클래스라는 권한이 있습니다클래스의 여러 인스턴스를 만들 수 없습니다.

//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 

왜 이런 일이 벌어지고 있는지 전혀 알 수 없으며 도움을 주시면 감사하겠습니다. 그것은 $permission_name 때마다 덮어 쓰는 것

+4

? 당신은 OOP의 근본적인 부분을 놓치고 있습니다. –

답변

0

내부 function __construct$permission_nameglobal이며, ->get_name()이 같은 global 변수를 반환하기 때문에 당신은 new 인스턴스를 호출합니다.

0

클래스에서 global $permission_name 행을 제거하십시오.

당신이 $this .so를, 당신은 현재 instance.something 등의 $permission_name에 액세스 할 수 $this->permission_name을 사용할 수 있습니다 사용하여 클래스의 현재 인스턴스를 참조 할 수 있습니다

, 왜 global``사용

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; 
    } 

} 
관련 문제