0
votes

I am learning cakePHP 1.26.
I got a Controller which got two functions.
I was thinking to make $myVariable a global variable so that both functions in the controllers can share it, but I am not sure if this is the best way to declare a global variable in cakePHP:

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

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

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

Please help if you could.


edited reason:

Hi Aircule,

I have altered a little bit to the code and followed your suggestion, but the value of myVariable was not changed at all:

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"
        }

     }
2
Why are you not using the latest version of cake (1.3.2)? - quantumSoup
@ Aircule. I have been learning cakePHP 1.26 for a few weeks, and I am more familiar with this version. - user327712
This is not a global variable, but rather a class variable. If you really wanted a global in cake, you would use Nik's suggestion regarding Configure:: - atp

2 Answers

6
votes
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";}
      }
 }

(note that as it is $newUser is undefined when you call the methods).

You should read this: http://php.net/manual/en/language.oop5.php

3
votes

Take a look on Configure class. You can Configure::write('var', $value) or Configure::read('var') and this is accessible on all parts of the application i.e. you can define variable in AppController::beforeFind() and you can access it in Model, View and all controllers of course.

But for your case the best answer is Class variables describes in the answer above. :)