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?
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
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With