PHP:无法从我的类的另一个方法包含的页面调用对象方法
我刚刚创建了一个类来控制我的php应用程序,我有一个大问题(我用了2天的时间来思考和搜索它,但找不到任何解决方案)。我的类包含一个名为PHP:无法从我的类的另一个方法包含的页面调用对象方法,php,oop,Php,Oop,我刚刚创建了一个类来控制我的php应用程序,我有一个大问题(我用了2天的时间来思考和搜索它,但找不到任何解决方案)。我的类包含一个名为register()的方法,该方法将脚本加载到页面中。我的班级是: class Apps { protected $_remember; // remember something public function register($appName) { include "$appName.php"; //include this php
register()
的方法,该方法将脚本加载到页面中。我的班级是:
class Apps
{
protected $_remember; // remember something
public function register($appName)
{
include "$appName.php"; //include this php script into other pages
}
public function set($value)
{
$this->_remember = $value; // try to save something
}
public function watch()
{
return $this->_remember; // return what I saved
}
}
在time.php
文件中
$time = 'haha';
$apps->set($time);
作为我问题的标题,当我纯粹将time.php
包含在main.php
中时,我可以使用$apps->set($time)
($apps
已在main.php
中定义)。像这样main.php
:
$apps = new Apps();// create Apps object
include "time.php";
echo $apps->watch(); // **this successfully outputs 'haha'**
但是当我从Apps类调用方法register()
以包含time.php
,我得到了未定义变量$Apps
和调用set方法的错误time.php
(对我来说,它好像不接受time.php
中的$Apps
)。我的main.php
是:
$apps = new Apps();// create Apps object
$apps->register('time'); // this simply include time.php into page and it has
//included but time.php doesn't accept $apps from main.php
echo $apps->watch(); // **this outputs errors as I said**
顺便说一下,我不擅长写作。如果你什么都不懂,就问我。感谢您的回复D如果希望第二个代码段正常工作,请将time.php
的内容替换为:
$time = 'haha';
$this->set($time); // instead of $apps->set($time);
由于此代码是由Apps
类的实例方法include
d生成的,因此它可以访问实例本身,$this
了解PHP中的变量范围。包含文件的范围在函数寄存器中开始和结束。要验证这一点,请使用var\u dump($this)代码>在要包含的PHP文件中,您将看到我谈论的范围:)这非常有用。我现在可以做了。非常感谢你,先生