【问题标题】:php variable object propertyphp变量对象属性
【发布时间】:2017-08-21 04:33:58
【问题描述】:

这可能看起来像重复,但我尝试了所有答案,但没有一个对我有帮助。 我有一个:

class Api extends Controller {
    private $host;
    function __construct() {
        parent::__construct();
    }
}

这部分我没有问题,因为 Api 类中的许多函数都在工作

我的问题如下:

function POS() {
    $host = defined('url_parameter_1') ? url_parameter_1 : null;
    $operation = defined('url_parameter_2') ? url_parameter_2 : null;
    $transaction_id = defined('url_parameter_3') ? url_parameter_3 : null;

    if ($host != null) { 
        $this->{$host};
    }
    else { 

    }

}

在这个例子中 url_parameter_1 = PashaBank 我有一个函数:

private function PashaBank() {
    $data = array();
    $params['logo'] = '/public/img/logo-pashabank.png';
    $params['description'] = 'Some description text';

    echo $this->build_html($params);
}

我得到一个错误

注意:未定义的属性:/var/www/vhosts/ 中的 Api::$$host

当我使用 $this->{'$host'};

和错误

未定义的属性:/var/www/vhosts/ 中的 Api::$PashaBank 当我使用 $this->{$host};

类完全如下所示:

class Api extends Controller {
    private $host;
    function __construct() {
        parent::__construct();
    }
    function POS() { 
        $host = defined('url_parameter_1') ? url_parameter_1 : null;
        $operation = defined('url_parameter_2') ? url_parameter_2 : null;
        $transaction_id = defined('url_parameter_3') ? url_parameter_3 : null;

        if ($host != null) { 
            $this->{$host};
        }
        else { 

        }   
    }

    function build_html($params) {
        $html = '<div class="pos_container">';
        $html .= '<div class="pos_header"><img src="'.$params['logo'].'" /></div>';
        $html .= '<div class="pos_body">';
        $html .= '<p class="pos_description">'.$params['description'].'</p>';

        $html .= '</div>'; // pos_body
        $html .= '</div>'; // pos_container

        return $html;
    }
    private function PashaBank() { 
        $data = array();
        $params['logo'] = '/public/img/logo-pashabank.png';
        $params['description'] = 'Some description text';

        echo $this->build_html($params);
    }   
}

请帮忙,我卡在这里

【问题讨论】:

  • 试试`$this->{$host}()`
  • 尝试将主机设置为 "" 而不是 null 并在 if 语句中检查 if(host!="")
  • @ChetanAmeta 你是我的英雄))该死的我怎么能错过()

标签: php variables object properties


【解决方案1】:

问题是我错过了对象属性之后的 ()。感谢@ChetanAmeta

正确的做法是:

$this->{$host}();

【讨论】:

    【解决方案2】:

    首先,您的班级没有名为“PashaBank”的字段。你可以看到通知的原因:

    注意:未定义的属性:/var/www/vhosts/ 中的 Api::$$host

    顺便说一句,没有理由使用语句:

    $this->{$host}

    代替:

    $this->$host

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 2017-07-05
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      相关资源
      最近更新 更多