簡體   English   中英

property_exists() 檢查 static 屬性是否存在於 class 方法中

[英]property_exists() to check if static property exists inside class method

我有一個 class 和 static 屬性和方法。 我的方法之一是動態屬性抓取器。 我想動態地執行此操作,以防止為我要返回的每個屬性提供一個方法。 單一的方法會更好。

我的問題是該方法返回“未定義的屬性”。 我在互聯網上嘗試了各種解決方案,但似乎沒有任何適合或工作。

Class 示例:

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

這就像屬性不存在一樣返回。 事實上,可見性並不重要,因為它們都像不存在一樣返回。 此外,我知道這在不使用 static 變量時有效。 我寧願繼續使用 static 變量。

從上面更新我的代碼以包含命名空間。 這是導致該方法返回未定義的問題。

更新后的代碼如下:

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;

Output:

Property: Generic::propA - A

Property: Generic::propB - B

Property: Generic::propC - C

Property: Generic::nonProp - Undefined Property

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM