在 cakePHP 中声明全局变量的最佳方法是什么
我正在学习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"
}
}
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"
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(请注意,当您调用方法时, $newUser 是未定义的)。
您应该阅读以下内容:http://php.net/manual/en/language.oop5。 php
(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
看一下配置类。您可以配置::write('var', $value)或Configure::read('var'),这可以在应用程序的所有部分访问,即您可以在AppController::beforeFind()中定义变量,并且可以访问当然,它存在于模型、视图和所有控制器中。
但对于您的情况,最好的答案是上面答案中描述的类变量。 :)
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. :)