简体   繁体   中英

php variable object property

this maybe seems like duplicate, but I tried all answers and none of them helped me. I have a:

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

I don't have problem with this part, because many functions inside Api class are working

my problem is with below:

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 { 

    }

}

in this example url_parameter_1 = PashaBank and I have a function:

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

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

i get an error

Notice: Undefined property: Api::$$host in /var/www/vhosts/

when i use $this->{'$host'};

and error

Undefined property: Api::$PashaBank in /var/www/vhosts/ when i use $this->{$host};

Class fully looks like this:

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

please help, i'm stuck in here

First of all, your class doesn't have field named "PashaBank". It's the reason of notice you can see:

Notice: Undefined property: Api::$$host in /var/www/vhosts/

By the way, there is no reason to use statement:

$this->{$host}

instead of:

$this->$host

the problem was that i missed the () after object property. Thanks to @ChetanAmeta

the correct way is:

$this->{$host}();

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