Reputation: 3321
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"
}
}
Upvotes: 0
Views: 7353
Reputation: 6047
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. :)
Upvotes: 3
Reputation: 28122
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
Upvotes: 6