Instantiating a vendor class in class constructor

前端 未结 1 408
礼貌的吻别
礼貌的吻别 2021-01-27 22:17

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

相关标签:
1条回答
  • 2021-01-27 22:54

    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();
    }
    

    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');
    
    0 讨论(0)
提交回复
热议问题