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 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题