【发布时间】:2014-12-10 20:29:16
【问题描述】:
在处理 PHP 中的继承时,我发现缺乏一些知识,主要是关于 constructors 和 private 属性。
我们以这段代码为例:
<?php
class Module
{
public $type;
public function __construct($type)
{
$this->type = $type;
}
}
class BModule extends Module
{
}
class CModule extends BModule
{
}
class A
{
private $module;
public function __construct(Module $module)
{
echo 'Set module for '.__CLASS__.' to '.$module->type . PHP_EOL;
echo "<br>";
$this->module = $module;
}
public function getModule()
{
echo "I (as " . __CLASS__ . ") have a module of type " . $this->module->type;
return $this->module->type;
}
}
class B extends A
{
}
$m = new Module('base-module');
$bm = new BModule('bi-module');
echo "<br>--------A---------<br>";
$a = new A($m);
echo "<br>A is of type " . $a->getModule();
echo "<br>--------B---------<br>";
$b = new B($bm);
echo "<br>B is of type " . $b->getModule();
一些问题:
- B构造不应该在B的上下文中调用构造函数吗? (所以我预计它会失败,因为它没有继承私有属性 $module)
- 或者 PHP 会简单地调用 A 构造函数,使用/引用来自 A 的方法和属性? (包括私人的)
- 我可以将 Module 或 BModule 对象传递给 $b;这是因为 BModule 是 Module 的子级。验证类型提示时,PHP 是否检查传递对象的某些继承链(检查父级)?
- 那么我可以将 Module 或 BModule 或 CModule 类型的对象传递给构造函数吗?
这是另一个例子:
<?php
class a
{
private $a;
protected $a_copy;
public function __construct($a_value)
{
$this->a = $a_value;
$this->a_copy = $this->a;
}
public function getA()
{
return $this->a;
}
public function getCopyA()
{
return $this->a;
}
}
class b extends a
{
}
$a = new a('value for a');
$b = new b('value for b');
echo "<br>-----A-----<br>";
echo $a->getA()."<br>";
echo $a->getCopyA()."<br>";
echo "<br>-----B-----<br>";
echo $b->getA()." (I would expect to have no access to \$a)<br>";
echo $b->getCopyA()."<br>";
作为 $a 私有属性,我希望无法访问它 或从类 b 对其进行任何操作. 对我的实际理解来说有点无厘头。
【问题讨论】:
标签: php oop inheritance type-hinting