简体   繁体   中英

How can I call a static method on a variable classname that is a property?

How can I call a static method on a variable classname that is a property?

Here is some example code:

class Foo
{
    var $class = 'Bar';

    public function getNew() {
        return $this->class::create(); // this fails
    }
}

class Bar
{
    public static function create() {
        return new self();
    }
}

$foo = new Foo();
$foo->getNew();

In this example, how can I call the static method on the class specified in the $class property?

Variable scope resolution fails with a parse error on PHP 5.6:

{$this->class}::create();
($this->class)::create();

This works but is so verbose:

$class = $this->class;
$class::create();

call_user_func([$this->class, 'create']);

Is there a shorter or more readable way? I'm using PHP 5.6

Mark's comment is spot on. This works:

<?php

class Foo {

    var $class = 'Bar';

    public function getNew() {
        $className = $this->class;
        return $className::create();
    }
}

class Bar {
    public static function create() {
        return new self();
    }

    public function speak() {
        echo 'It lives';
    }
}

$foo = new Foo();
$bar = $foo->getNew();
$bar->speak();

However, don't be afraid of it being verbose, because it is very clear. And PHP has many other verbose constructs to worry about.

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