如何基于同一类中对象的变量调用函数?

时间:2018-08-23 12:17:23

标签: php

我知道如何基于这样的变量调用函数:

$platform->ConfigurePlatform($client);

$platform是包含类名称的变量。

我试图调用这样的函数,但是对象来自同一类。以下将正常工作,这适用于相同的方法。

$platform = new $platform_name();
$platform->ConfigurePlatform($client);

但是我想像这样在对象内调用另一个方法:

$this->$platform->GetOrdersFromPlatform();

这将产生以下错误:

  

致命错误:无法访问空属性(在上面的行中)

我想也许我应该像这样创建对象:

$this->$platform = new $platform_name();

但这会导致以下错误:

  

致命错误:无法访问空属性(在上面的行中)

我该如何实现?

2 个答案:

答案 0 :(得分:2)

您的问题尚不清楚,但是我认为您想要的是方法链接,这可以通过返回类的$this属性来完成。示例:

class ClassName
{
    function ConfigurePlatform($client)
    {
        // What to do
        echo __METHOD__.": ".$client."\n";

        // return the $this property to make the class properties chainable
        return $this;
    }

    function GetOrdersFromPlatform($client)
    {
        // What to do
        echo __METHOD__.": ".$client."\n";

        // return the $this property to make the class properties chainable
        return $this;
    }
}


$classObj = new ClassName();

$client = "Firefox/Chrome/Safari";

// Call both methods

$classObj->ConfigurePlatform($client)->GetOrdersFromPlatform($client);
//ClassName::ConfigurePlatform: Firefox/Chrome/Safari ClassName::GetOrdersFromPlatform: Firrefox/Chrome/Safari

答案 1 :(得分:0)

如果计划在类的不同位置使用同一对象,则只需将其设置为同一类的属性即可。

class Station
{
    public $platform = null;

    public function start()
    {
        $this->platform = new Platform();

        $this->platform->ConfigurePlatform('test');
    }

    public function getOrders()
    {
        return $this->platform->GetOrdersFromPlatform();
    }
}

class Platform
{
    private $orders = null;

    public function ConfigurePlatform($string)
    {
        $this->orders = $string;

        return $this;
    }

    public function GetOrdersFromPlatform()
    {
        return $this->orders;
    }
}


$test = new Station();
$test->start();

echo $test->platform->GetOrdersFromPlatform();
//or
echo $test->getOrders();

这是经过测试的代码:https://3v4l.org/UuTgb

相关问题