注意:使用未定义的常量自我假设'self',当将property_exists作为第一个参数放入时

Raf*_*del 6 php oop properties constants self

我正在尝试使用self而不是在propery_exists函数内键入类名,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行这个脚本时,它会出错:

注意:在第36行的/var/www/photo_gallery/includes/User.php中使用未定义的常量自我假设'self'

第36行property_exists是调用方法的行.

当我改变自己User(班级名称).它完美地运作.

我想知道为什么使用self这样的通知?不self参考课程?

Vah*_*aji 5

self指当前类。不是类名

尝试使用魔术常量:

if(isset($user->$name) || property_exists(__CLASS__, $name)){
Run Code Online (Sandbox Code Playgroud)

从 php 手册: __CLASS__

班级名称。(在 PHP 4.3.0 中添加)从 PHP 5 开始,该常量返回声明时的类名(区分大小写)。在 PHP 4 中,它的值总是小写的。类名包括它在其中声明的命名空间(例如 Foo\Bar)。请注意,从 PHP 5.4 开始,CLASS也适用于特征。在 trait 方法中使用时,CLASS是使用该 trait 的的名称。

PHP 手册

一个例子:

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

$test = new Test();
Run Code Online (Sandbox Code Playgroud)

输出:

Test
Run Code Online (Sandbox Code Playgroud)