我已经看到几个问题与真正相似的标题,但它们与我的具体问题无关.
基本上,我想在扩展核心的类中从我的核心类访问变量,但与其他示例相比,事情似乎相当复杂.我正在使用MVC框架.我已经简化了下面的代码来删除任何不相关的内容.
的index.php
// Load the core
include_once('core.php');
$core = new Core($uri, $curpath);
$core->loadController('property');
Run Code Online (Sandbox Code Playgroud)
core.php中
class Core
{
public $uri;
public $curpath;
function __construct($uri, $curpath)
{
$this->uri = $uri;
$this->curpath = $curpath;
}
// Load the controller based on the URL
function loadController($name)
{
//Instantiate the controller
require_once('controller/'.$name.'.php');
$controller = new $name();
}
}
Run Code Online (Sandbox Code Playgroud)
property.php
class Property extends Core
{
function __construct()
{
print $this->curpath;
}
}
Run Code Online (Sandbox Code Playgroud)
打印$ this-> curpath只返回任何内容.变量已设置但为空.如果我在core.php中打印$ this-> curpath就打印好了.
我该如何访问这个变量?
你做错了TM
您应该使用自动加载器,而不是手动包含每个类的文件.您应该了解spl_autoload_register()和命名空间,以及如何利用它们.
不要在__construct()方法中生成输出.这是一个非常糟糕的做法
变量仍在那里.那不是问题.在PHP中,当您扩展类时,它不会继承构造函数.
你不明白继承是如何工作的.在扩展类的实例上调用方法时,在调用扩展类的方法之前,它不会执行父类的方法.他们被覆盖,而不是堆叠.
不应公开对象变量.你打破了封装.相反,og定义它们public应该使用protected.
你应该扩展他们不同类型的类一般的东西.在extendsPHP中意味着是-A .这意味着,当你写作时class Oak extends Tree,你的意思是所有的橡树都是树木.同样的规则意味着,在您的理解中,所有Property实例都只是实例的特例Core.他们显然不是.