如何知道静态属性是否在php中继承?

Mat*_*rix 9 php oop inheritance static class

我有一个 $class_name = 'B';

而且:

class A
{
    static $foo = 42;
    static $baz = 4;
}

class B extends A
{
   static $bar = 2;
   static $baz = 44;
}
Run Code Online (Sandbox Code Playgroud)

我怎么知道$class_name::$foo$ class_name的静态属性是否是继承的静态属性?

我需要以下结果:

$class_name = 'A';
isOwnStaticProperty($class_name, 'foo'); //TRUE : is a static property of this class

$class_name = 'B';
isOwnStaticProperty($class_name, 'foo'); //FALSE : is NOT a static property of this class

$class_name = 'B';
isOwnStaticProperty($class_name, 'bar'); //TRUE : is a static property of this class

$class_name = 'A';
isOwnStaticProperty($class_name, 'bar'); //FALSE : is NOT a static property of this class

$class_name = 'B';
isOwnStaticProperty($class_name, 'baz'); //TRUE : is a static property of this class

$class_name = 'A';
isOwnStaticProperty($class_name, 'baz'); //TRUE : is a static property of this class
Run Code Online (Sandbox Code Playgroud)

如何实现isOwnStaticProperty()功能?

Adr*_*uer 7

您可以将ReflectionClass与getProperties方法一起使用来检索反射的属性.要过滤,您可以使用ReflectionProperty

<?php

class A
{
    static $foo = 42;
    static $baz = 4;
}

class B extends A
{
   static $bar = 2;
   static $baz = 44;
}

function isOwnStaticProperty($class, $prop) {
    $reflect = new ReflectionClass($class);
    //Filtering only the statics values with ReflectionProperty::IS_STATIC
    $props   = $reflect->getProperties(ReflectionProperty::IS_STATIC);
    foreach ($props as $object) {
        if($object->class == $class && $object->name == $prop) {
            return true;
        }    
    }
    return false;
}   


$class_name = 'A';
echo isOwnStaticProperty($class_name, 'foo') ? "TRUE<br>\n" : "FALSE<br>\n"; 

$class_name = 'B';
echo isOwnStaticProperty($class_name, 'foo') ? "TRUE<br>\n" : "FALSE<br>\n"; 

$class_name = 'B';
echo isOwnStaticProperty($class_name, 'bar') ? "TRUE<br>\n" : "FALSE<br>\n"; 

$class_name = 'A';
echo isOwnStaticProperty($class_name, 'bar') ? "TRUE<br>\n" : "FALSE<br>\n"; 

$class_name = 'B';
echo isOwnStaticProperty($class_name, 'baz') ? "TRUE<br>\n" : "FALSE<br>\n"; 

$class_name = 'A';
echo isOwnStaticProperty($class_name, 'baz') ? "TRUE<br>\n" : "FALSE<br>\n"; 
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

TRUE
FALSE
TRUE
FALSE
TRUE
TRUE