简体   繁体   中英

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() ?

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:

class MyClass { private string $className; public 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::

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM