0

我正在学习 cakePHP 1.26。
我有一个控制器,它有两个功能。
我正在考虑使 $myVariable 成为全局变量,以便控制器中的两个函数可以共享它,但我不确定这是否是在 cakePHP 中声明全局变量的最佳方法:

class TestingController extends AppController {  
     var $myVariable="hi there";

    function hello(){
     if($newUser){echo $myVariable;}
      }

     function world(){
      if($newUser=="old"){$myVariable="hi my friends";}
      }
 }

如果可以,请提供帮助。


编辑原因:

嗨,Aircule,

我对代码进行了一些更改并遵循了您的建议,但 myVariable 的值根本没有改变:

class TestingController extends AppController {  
         var $myVariable="hi there";

        function hello(){
         echo $this->myVariable;
          }

         function world(){
          $this->myVariable="hi my friends";
          }

         function whatValue(){
         echo $this->myVariable;  // still output "hi there"
        }

     }
4

2 回答 2

6
class TestingController extends AppController {  
     var $myVariable="hi there";

    function hello(){
     if($newUser){echo $this->myVariable;}
      }

     function world(){
      if($newUser=="old"){$this->myVariable="hi my friends";}
      }
 }

(请注意,调用方法时 $newUser 未定义)。

你应该阅读这个: http: //php.net/manual/en/language.oop5.php

于 2010-07-17T17:14:16.670 回答
3

看看配置类。您可以 Configure::write('var', $value) 或 Configure::read('var') 这可以在应用程序的所有部分访问,即您可以在 AppController::beforeFind() 中定义变量并且您可以访问当然,它在模型、视图和所有控制器中。

但是对于您的情况,最好的答案是上面答案中描述的类变量。:)

于 2010-07-17T17:37:18.790 回答