簡體   English   中英

PHP:如何從屬性“className”實例化 class

[英]PHP: How to instantiate a class from a property 'className'

想象一下這段代碼:

class MyClass
{
    private string $className;
    public function __construct(string $className)
    {
        $this->className = $className;
    }

    public function instantiateClass()
    {
        $className = $this->className;
        return new $className();
    }
}

有沒有辦法實例化 class 而不首先在方法instantiateClass()中將屬性值分配給局部變量$className

像這樣的東西:

class MyClass
{
    private string $className;
    public function __construct(string $className)
    {
        $this->className = $className;
    }

    public function instantiateClass()
    {
        // This cannot be done as 'className' should be a method, not the property
        return new $this->className();
    }
}

有任何想法嗎?

因此,正如@Cid 在我的問題下面的評論中指出的那樣,解決方案實際上是我認為錯誤的解決方案:

class MyClass { 私有字符串 $className; 公共 function __construct(string $className) { $this->className = $className; }

public function instantiateClass()
{
    // This works! It doesn't find a method, but reads the property correctly!
    return new $this->className();
}

}

您可以使用__CLASS__self::static::

你可以試試

class MyClass
{

    public function __construct()
    {
    }

    static public function instantiateClass()
    {
        return new self();
    }

    static public function instantiateClassWithStatic()
    {
        return new static();
    }

}

$myInstance = MyClass::instantiateClass();

暫無
暫無

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

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