Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 属性_exists()检查类方法中是否存在静态属性_Php_Oop - Fatal编程技术网

Php 属性_exists()检查类方法中是否存在静态属性

Php 属性_exists()检查类方法中是否存在静态属性,php,oop,Php,Oop,我有一个具有静态属性和方法的类。我的方法之一是动态属性抓取器。我希望动态地执行此操作,以防止为要返回的每个属性使用方法。单一的方法会更好 我的问题是该方法返回“Undefined属性”。我曾在互联网上尝试过各种解决方案,但似乎都不合适,也不管用 课堂示例: class Generic { public static $propA = "A"; private static $propB = "B"; protected static

我有一个具有静态属性和方法的类。我的方法之一是动态属性抓取器。我希望动态地执行此操作,以防止为要返回的每个属性使用方法。单一的方法会更好

我的问题是该方法返回“Undefined属性”。我曾在互联网上尝试过各种解决方案,但似乎都不合适,也不管用

课堂示例:

class Generic
{
    public static $propA = "A";
    private static $propB = "B";
    protected static $propC = "C";

    public static function getProperty(string $property): string
    {
        if (!property_exists('Generic', $property)) :
            return "Undefined Property";
        endif;

        return self::$$property;
    }
}
用法:

print_r(Generic::getProperty('propA'));

这会返回,就像属性不存在一样。事实上,可见性并不重要,因为它们都会返回,就好像它们不存在一样。另外,我知道这在不使用静态变量时是有效的。我宁愿继续使用静态变量。

从上面更新代码以包含名称空间。这就是导致该方法返回undefined的问题

更新后的代码如下:

class Generic
{
    public static $propA = "A";
    private static $propB = "B";
    protected static $propC = "C";

    public static function getProperty(string $property): string
    {
        if (!property_exists('JLDN\Generic', $property)) :
            return "Undefined Property";
        endif;

        return self::$$property;
    }
}

foreach (['propA', 'propB', 'propC', 'nonProperty'] as $prop) :
    printf("<p>Property: %s::%s - %s</p>\n", 'Generic', $prop, print_r(Generic::getProperty($prop), true));
endforeach;

代码看起来工作正常?我看到代码在您提供的链接中工作。这是一种奇怪的行为,因为代码在我的测试服务器上没有按预期工作。我想知道它是否是拉拉贡的设置/配置。
Property: Generic::propA - A

Property: Generic::propB - B

Property: Generic::propC - C

Property: Generic::nonProp - Undefined Property