开发者

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

Is there an equivalent of this JavaScript code in PHP?

开发者_运维技巧
var object = {}, key;
Object.hasOwnProperty.call(object, key) 


Or using reflection (See: 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));


for properties:

property_exists($class_instance, 'YourProperty');

for methods:

method_exists($class_instance, 'YourMethod');

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

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


Here is my approach using reflection. http://php.net/manual/en/class.reflectionclass.php

Let's say I have this configuration:

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';
}

I define this function in my base class:

class A
{
    // ...

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

Then I can call it from the base class itself and any child class:

>>> A::hasOwnProperty('name');
=> true

>>> B::hasOwnProperty('name');
=> false

>>> C::hasOwnProperty('name');
=> true

>>> D::hasOwnProperty('name');
=> true

Notice that it returns true even if the value is null, which is the expected behaviour I think. That seems to take the best of both isset() and property_exists().

Keep in mind that reflection is a performance-hitting process though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜