Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:无法从我的类的另一个方法包含的页面调用对象方法_Php_Oop - Fatal编程技术网

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

PHP:无法从我的类的另一个方法包含的页面调用对象方法,php,oop,Php,Oop,我刚刚创建了一个类来控制我的php应用程序,我有一个大问题(我用了2天的时间来思考和搜索它,但找不到任何解决方案)。我的类包含一个名为register()的方法,该方法将脚本加载到页面中。我的班级是: class Apps { protected $_remember; // remember something public function register($appName) { include "$appName.php"; //include this php

我刚刚创建了一个类来控制我的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
,我得到了
未定义变量$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文件中,您将看到我谈论的范围:)这非常有用。我现在可以做了。非常感谢你,先生