在类构造函数中实例化供应商类 [英] Instantiating a vendor class in class constructor
问题描述
在我的CakePHP 2应用程序中,我有这样的供应商。我需要在我的控制器类中创建一个这个供应商类的实例。所以我将在控制器的不同函数中使用该实例。
In my CakePHP 2 application I have such vendor. I need to create an instance of this vendor class inside my controller class. So I will use that instance inside my controller's different functions.
App::import('Vendor', 'fancyVendor', array('file' => 'fancyVendor.php'));
class MyController extends AppController {
public $fancyVendor;
function beforeFilter() {
$fancyVendor = new fancyVendor();
$fancyVendor->setValue("12");
}
function showMe() {
echo $fancyVendor->getValue();
}
}
在我的 showMe ,我不能得到我在 beforeFilter 函数中设置的值。是否有正确的实例化方法?
Inside my showMe function, I can't get the value that I set inside my beforeFilter function. Is there a proper way to instantiate it?
推荐答案
您需要了解 scope 。您已在 beforeFilter()
作用域中初始化了一个变量,然后尝试在 showMe
作用域中使用它。两个是完全不同的。
You need to learn about scope. You have initialised a variable in the beforeFilter()
scope and then trying to use it in the showMe
scope. The two are completely different.
您可以创建一个范围限定为整个类的变量,通常称为属性...
You can make a variable that is scoped to the entire class, normally called a property...
function beforeFilter() {
$this->fancyVendor = new fancyVendor();
$this->fancyVendor->setValue("12");
}
function showMe() {
echo $this->fancyVendor->getValue();
}
另一点要注意的是,您可以使用 App :: uses()
方法来加载类。根据你的命名它会工作。 (类是以这种方式加载的)
Another point to note is that you can use the App::uses()
method to load the class. According to your naming it would work. (class is lazy loaded this way)
App::uses('fancyVendor', 'Vendor');
这篇关于在类构造函数中实例化供应商类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!