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 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁
  • ¥15 bywave配置文件写入失败
  • ¥20 基于Simulink的ZPW2000轨道电路仿真
  • ¥15 pycharm找不到在环境装好的opencv-python
  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题