简体   繁体   中英

PHP call method of class where class name is in field of other class

I have a CodeIgniter php setup and enhanced it with RESTful capabilities.

I have the following structure

base.php (this is the base controller class

class Base {
    private $model
    public function __construct($model = false) {
        $this->model = $model . '_model';
        $this->load->model($this->model);
    ...
}

And then a controller which specifies a model

class Products extends Base {

    public function __construct() {
        parent::__construct('product');     
    }
}

The problem is as follows: in base.php I have functions for HTTP methods (get, post, put, delete), but I am not able to call a static method from the model like so:

public function get() {
    return $this->model::loadData();
}

If I assign $this->model to a local variable in get() it works, but it looks ugly to me.

So my question is: how can I call a static method of a class A given the class name in a member of class B without assigning it to a new local variable in methods of class B?

PS: I know CodeIgniter does not look like this, but the structure of it is irrelevant to my problem.

As you point out, assigning $this->model to a local variable like $model and then calling $model::loadData() works as expected.

The fact that the $this->model::loadData() call doesn't work might have to do we precedence between the :: and -> operators, but I can't say for sure as there's no reference to these in the official documentation.

For operators of equal precedence, left associativity means that evaluation proceeds from left to right, and right associativity means the opposite. For operators of equal precedence that are non-associative those operators may not associate with themselves. So for example, the statement 1 < 2 > 1, is illegal in PHP. Whereas, the statement 1 <= 1 == 1 is not, because the T_IS_EQUAL operator has lesser precedence than the T_IS_SMALLER_OR_EQUAL operator.

from PHP Operator Precedence .

I might be way off here, but from the behaviour of your code I'd say they're either the same precedence or :: has a higher precedence than -> , hence not usable together as you intended.

UPDATE

It confirms, the :: operator has higher precedence that -> therefore PHP interprets this:

$this->model::loadData();

as

($this->(model::loadData()));

Check the answer for the $var::staticfunction() OK but $this->var::staticfunction() NOT. What's the rationale? question.

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