views:

61

answers:

2

Hi all,

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

     }
+4  A: 
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

quantumSoup
@ Aircule. Is it {$this->myVariable;} or {$this->$myVariable;} Do I need to add a dollar sign before myVaraible?
You use `$this->myVariable` and `$this->myFunction()` when you are accessing a class variable or method.
quantumSoup
Have you taken a look at [Bake](http://book.cakephp.org/view/113/Code-Generation-with-Bake) ?
quantumSoup
@ Aircule. Sorry I didn't read that
@ Aircule. Thank you for the help.
Just to note, this is not cakePHP specific. This is an essential feature of PHP or any OOP language. Also, I'd use "private" instead of "var" for the member variable declaration.
Mike Sherov
@ Aircule. I have followed your suggestion, but the value of $myVariable still did not get changed by {$this->myVariable="hi my friends";}
@kwokwai It should have been; at least for that particular instance of the object. I suspect it's not changing because it doesn't reach that point in the code, since `$newUser` is undefined and the `if` statement evaluates to false.
quantumSoup
+2  A: 

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. :)

Nik