在类构造函数中实例化供应商类

编程入门 行业动态 更新时间:2024-10-27 02:28:03
本文介绍了在类构造函数中实例化供应商类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的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');

更多推荐

在类构造函数中实例化供应商类

本文发布于:2023-11-04 10:09:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557643.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例   供应商

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!