【发布时间】:2013-05-09 06:42:08
【问题描述】:
我正在尝试让子类(提要)从主类(控制器)继承一个变量。
我有 3 个文件。它们如下所示。
核心文件:
/* ----------------------------- *
* LOAD THE CONTROLLER CLASS NOW *
* ----------------------------- */
require(CORE_PATH . 'controller.php');
require(CORE_PATH . 'load_controller.php');
控制器类:
<?php
class Controller {
var $sessions, $a;
public function __construct() {
$this->sessions = new Sessions();
$this->a = 'yo';
}
}
饲料类:
class Feeds extends Controller {
public function feeds() {
/* We can load other resources here */
}
function index($val) {
echo $this->a;
}
}
修复:
<?php require(PROTECT);
class Controller {
protected $variable = "Setting the variable right here works.";
public function __construct() {
$this->variable = "Setting it right here will only work for the current object. It's as if variable isn't being set at all when it comes to other classes.";
}
}
【问题讨论】:
-
类相关并不意味着单独的对象实例将共享相同的数据。这不是它的工作原理。
-
@deceze - 这不是我想要做的。在这种情况下,实例是微不足道的。我只是想从 Controller 类继承 $a 和 $sessions 到扩展控制器的 Feeds 类。当我尝试使用 $this 关键字访问 $a 变量时,它不起作用。
-
另外,将变量范围从“var”更改为“Public”或“public static”或“static”也不起作用。
-
@deceze - 实际上,现在我再看一遍,你是对的!当我应该在构造函数方法之前设置它时,我依靠构造函数方法来设置变量的值。谢谢!
标签: php class variables object inheritance