Object.hasOwnProperty.call(object, key) in php

Object.hasOwnProperty.call(object, key) in php

本文关键字:key in php object hasOwnProperty call Object      更新时间:2023-09-26

PHP中是否有这个JavaScript代码的等价物?

var object = {}, key;
Object.hasOwnProperty.call(object, key) 

或者使用反射(参见:http://www.php.net/manual/en/book.reflection.php):

<?php
$obj = (object)array('test' => 1);
$key = 'test';
$refObj = new ReflectionObject($obj);
var_dump($refObj->hasProperty($key));

对于属性:

property_exists($class_instance, 'YourProperty');

对于方法:

method_exists($class_instance, 'YourMethod');

http://php.net/manual/en/function.property-exists.php

http://php.net/manual/en/function.method-exists.php

这是我使用反射的方法。 http://php.net/manual/en/class.reflectionclass.php

假设我有以下配置:

class A
{
    protected static $name = 'blabla';
}
class B extends A
{
    //
}
class C extends A
{
    protected static $name = null;
}
class D extends A
{
    protected static $name = '324';
}

我在基类中定义了这个函数:

class A
{
    // ...
    public static function hasOwnProperty($property_name)
    {
        $property = (new 'ReflectionClass(static::class))->getProperty($property_name);
        return $property->class === static::class;
    }
}

然后我可以从基类本身和任何子类调用它:

>>> A::hasOwnProperty('name');
=> true
>>> B::hasOwnProperty('name');
=> false
>>> C::hasOwnProperty('name');
=> true
>>> D::hasOwnProperty('name');
=> true

请注意,即使值为 null,它也返回 true ,这是我认为的预期行为。这似乎需要isset()property_exists()的最好。

请记住,反射是一个影响性能的过程。