Notice: Use of undefined constant self - assumed 'self' , When put in property_exists as the first argument

Rafael Adel picture Rafael Adel · Aug 23, 2013 · Viewed 7.7k times · Source

I'm trying to use self instead of typing the class name inside 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 get an error :

Notice: Use of undefined constant self - assumed 'self' in /var/www/photo_gallery/includes/User.php on line 36

Line 36 is the line where property_exists method is called.

When i change self to User (the class name). It works perfectly.

I want to know why using self is giving such a notice ? Doesn't self refer to the class?

Answer

Vahid Hallaji picture Vahid Hallaji · Aug 23, 2013

Use self to refer to the current class. Not class name.

Try using magic constants:

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

From php manual: __CLASS__

The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 CLASS works also in traits. When used in a trait method, CLASS is the name of the class the trait is used in.

PHP Manual

An example:

class Test {
    public function __construct(){
        echo __CLASS__;
    }
}

$test = new Test();

Output:

Test