简体   繁体   English

PHP:如何从属性“className”实例化 class

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

Imagine this code:想象一下这段代码:

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

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

Is there a way to instantiate the class without first assigning the property value to the local variable $className in method instantiateClass() ?有没有办法实例化 class 而不首先在方法instantiateClass()中将属性值分配给局部变量$className

Something like this:像这样的东西:

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();
    }
}

Any ideas?有任何想法吗?

So, as pointed out by @Cid in the comments below my question, the solution is actually the one I thought was wrong:因此,正如@Cid 在我的问题下面的评论中指出的那样,解决方案实际上是我认为错误的解决方案:

class MyClass { private string $className; class MyClass { 私有字符串 $className; public function __construct(string $className) { $this->className = $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();
}

} }

you can use __CLASS__ or self:: or static::您可以使用__CLASS__self::static::

you can try你可以试试

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