PHP:不能从我的类的另一个方法包含的页面调用对象方法

时间:2013-11-07 20:17:48

标签: php oop

我刚刚创建了一个类来控制我的php应用程序,我有一个大问题(我使用2天思考和搜索它但找不到任何解决方案)。我的类包含一个名为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时,我undefined variable $apps收到错误call set method from none objecttime.php(听起来就像它没有'接受$apps里面的time.php给我。我的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

1 个答案:

答案 0 :(得分:0)

如果您希望第二个代码段有效,请将time.php的内容替换为:

$time = 'haha';

$this->set($time); // instead of $apps->set($time);

由于此代码includeApps类的实例方法,因此它可以访问实例本身$this