繁体   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