dongshun5963 2013-04-19 09: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 10: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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?