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


PHP : Can not call object method from a page which included by another method of my class

我刚刚创建了一个类来控制我的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 并为time.php call set method from none object(听起来它不接受$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

如果您希望第二个代码片段正常工作,请将time.php的内容替换为:

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

由于此代码由 Apps 类的实例方法include,因此它将有权访问实例本身,$this .