如何通过class():: function()将参数传递给php类

时间:2017-03-28 04:56:53

标签: php class

如何通过class()::function()将参数传递给PHP类?

class greenHouse{
    public function __construct(connection $con){
    }

    public function show(){
    }

}

$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();

作品

$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();

不起作用

我想将参数传递给$nameclass($con)::$namefunction();的类。我如何在PHP中执行此操作?

2 个答案:

答案 0 :(得分:0)

您正尝试使用该表示法静态调用函数...

$nameclass = 'greenHouse';
$namefunction = 'show';
$class = new $nameclass($con);
$class->$namefunction();

答案 1 :(得分:0)

您可以通过在大括号内调用new来实例化对象并立即将其丢弃:

class Test
{
    private $name;

    function __construct($name)
    {
        $this->name = $name;
    }

    function speak()
    {

        echo $this->name;
    }

    function __destruct()
    {
        echo 'dead';
    }
}
$class='Test';
$method='speak';


(new $class('David'))->$method();

echo ' is ';

$temp = new $class('John');
$temp->$method();

echo ' is ';

//Daviddead is John is dead

所以在你的情况下:

(new $nameclass($con))->$namefunction();