dongshun5963 2013-04-19 01:20
浏览 58
已采纳

类的PHP调用方法,其中类名在其他类的字段中

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?

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

  • 写回答

1条回答 默认 最新

  • doufang7385 2013-04-19 02:34
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部