【问题标题】:PHP $this not assigned to a variablePHP $this 未分配给变量
【发布时间】:2016-05-12 16:28:24
【问题描述】:

我知道 PHP OOP 的基础知识,但我只是注意到我在网上阅读的一些代码中的一些内容。请看下面:

class ControllerCheckoutCart extends Controller {

public function index() {
    $this->load->language('checkout/cart');

    $this->document->setTitle($this->language->get('heading_title'));

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
        'href' => $this->url->link('common/home'),
        'text' => $this->language->get('text_home')
    );

    $data['breadcrumbs'][] = array(
        'href' => $this->url->link('checkout/cart'),
        'text' => $this->language->get('heading_title')
    );
  } 
}

我了解$this-load-language('checkout/cart'); 从结帐文件夹中的购物车文件中收集返回信息的语法,但如果$this 未分配给变量,Index 方法如何使用此语法?例如,href' => $this->url->link('common/home') 这行对我来说非常有意义。

从 common/home 文件收集的数据被分配给数组中的href,然后我可以使用它...但是结帐/购物车信息存储在哪里,以便 Index 方法可以使用是吗?

我尝试用 Google 搜索这个,但是当我用 Google 搜索“PHP $this 未分配给变量”时,我收到了很多不必要的信息。

非常感谢您的帮助。

【问题讨论】:

  • 我不完全确定,但是根据我的说法,当您使用类对象调用此索引函数时,该函数将结帐/购物车语言加载到内存中,直到函数执行未结束,因为这对当前可用程序执行下一行代码就能从中获取数据。

标签: php class oop variables methods


【解决方案1】:
class Foo {

    protected $bar;

    public function baz() {
        $this->bar = 'baz';
    }

}

class Controller {

    protected $foo;

    public function __construct() {
        $this->foo = new Foo;
    }

    public function index() {
        $this->foo->baz();
    }

}

这就是你所看到的。 ->load->language(..)load 或其他对象的内部状态做了一些事情。它不需要有返回值就可以做一些有用的事情。

【讨论】:

  • 有趣,谢谢。有没有办法让我找出从哪个文件 load() 被调用,所以我可以看看对它做了什么?
  • 最好弄清楚load 是什么,然后阅读它的类定义和/或文档。见var_dump($this->load),你应该能够确定它的类,然后搜索它。
猜你喜欢
  • 2016-09-27
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
相关资源
最近更新 更多