0

我刚刚创建了一个类来控制我的 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.phpinto时main.php,我可以使用$apps->set($time)($apps已定义 in main.php)。像这样main.php

$apps = new Apps();// create Apps object

include "time.php";

echo $apps->watch(); // **this successfully outputs 'haha'**

register()但是当我从 Apps 类调用方法时include time.php,我得到了错误undefined variable $appscall set method from none objectfor time.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

4

1 回答 1

0

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

$time = 'haha';

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

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

于 2013-11-07T20:49:55.800 回答