Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 824
Rafael Adel Avatar asked Aug 23 '13 15:08

Rafael Adel


2 Answers

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
like image 195
Vahid Hallaji Avatar answered Oct 21 '22 07:10

Vahid Hallaji


You can use self::class this way you avoid magic constants.

As an addition you can use something like this to make an instance from an array:

public function __construct(array $array)
{
    foreach ($array as $key => $value) {
        if (property_exists(self::class, $key)) {
            $this->$key = $value;
        }
    }
}
like image 32
Kanabos Avatar answered Oct 21 '22 08:10

Kanabos