2010-07-17 71 views
0

我在學CakePHP 1.26。
我有一個控制器,它有兩個功能。
我想使$ MYVARIABLE一個全局變量,以便在控制器兩種功能可以共享,但我不知道這是否是在CakePHP中聲明一個全局變量的最佳方式:
什麼是在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" 
     } 

    } 
+0

爲什麼你不使用最新版本的蛋糕(1.3.2)? – quantumSoup 2010-07-17 17:21:31

+0

@ Aircule。我一直在學習CakePHP 1.26幾周,而且我對這個版本更加熟悉。 – user327712 2010-07-17 17:40:28

+0

這不是全局變量,而是一個類變量。如果你真的想要一個全球性的蛋糕,你會使用Nik的配置:: – ash 2010-07-17 18:41:56

回答

3

就以配置類看看。你可以配置:: write('var',$ value)或Configure :: read('var'),並且這個應用程序的所有部分都可以訪問,也就是說你可以在AppController :: beforeFind()中定義變量,並且你可以訪問它在模型,視圖和所有控制器當然。

但是對於你的情況,最好的答案是上面的答案中描述的類變量。 :)

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

+0

@ Aircule。它是{$ this-> myVariable;}或{$ this - > $ myVariable;} 我需要在myVarible之前添加美元符號嗎? – user327712 2010-07-17 17:16:50

+0

當您訪問類變量或方法時,您可以使用'$ this-> myVariable'和'$ this-> myFunction()'。 – quantumSoup 2010-07-17 17:17:58

+0

你看過[Bake](http://book.cakephp.org/view/113/Code-Generation-with-Bake)嗎? – quantumSoup 2010-07-17 17:19:12

相關問題