Note: using the undefined constant of the self-assumed self when placed in property_exists as the first argument

I am trying to use self instead of entering the class name inside the propery_exists function as follows:

 private static function instantiate($record){ $user = new self; foreach($record as $name => $value){ if(isset($user->$name) || property_exists(self, $name)){ $user->$name = $value; } } return $user; } 

But when I ran this script, it got an error:

Note: using the undefined self-constant is assumed to be 'self' in / var / www / photo _gallery / includes / User.php on line 36

Line 36 is the line in which the property_exists method is called.

When I change self to User (class name). It works great.

I want to know why using self gives such a notification? Does self belong to the class?

+6
source share
1 answer

Use self to indicate the current class. Not a class name .

Try using magic constants:

 if(isset($user->$name) || property_exists(__CLASS__, $name)){ 

From php reference: __CLASS__

Class name. (Added in PHP 4.3.0). Starting with PHP 5, this constant returns the class name as declared (case sensitive). In PHP 4, its value is always decreasing. The class name includes the namespace in which it was declared (for example, Foo \ Bar). Please note that with PHP 5.4, CLASS also works in outline. When used in an attribute method, CLASS is the name of the class in which the attribute is used.

PHP manual

Example:

 class Test { public function __construct(){ echo __CLASS__; } } $test = new Test(); 

Output:

 Test 
+3
source

Source: https://habr.com/ru/post/952371/


All Articles