【问题标题】:property_exists() to check if static property exists inside class methodproperty_exists() 检查类方法中是否存在静态属性
【发布时间】:2020-07-14 12:14:31
【问题描述】:

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

我的问题是方法返回“未定义的属性”。我在互联网上尝试了各种解决方案,但似乎没有一个适合或有效。

类示例:

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

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

【问题讨论】:

  • 代码看起来运行良好? 3v4l.org/u2g7K
  • 我看到代码在您提供的链接中有效。这是一种奇怪的行为,因为代码在我的测试服务器上没有按预期工作。我想知道它是否是 Laragon 中的设置/配置。

标签: php oop


【解决方案1】:

从上面更新我的代码以包含命名空间。这是导致该方法返回未定义的问题。

更新后的代码如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2013-05-19
    • 2012-12-20
    • 2012-02-02
    相关资源
    最近更新 更多