是否可以阻止子类中父类的函数可见性?
class DB {
function connect() {
// connects to db
}
}
class OtherClass extends DB {
function readData() {
// reads data
}
}
class AnotherOtherClass extends OtherClass {
function updateUser($username) {
// add username
}
}
如果我要写:
$cls1= new OtherClass();
$cls1->connect(); // want to allow this class to show
$cls2= new AnotherOtherClass();
$cls2->connect(); // do not want this class to show
$cls2->readData(); // want to allow this class to show
这可能吗?
答案 0 :(得分:1)
听起来好像实际希望AnotherOtherClass
延长OtherClass
。也许你想要消费/包装/装饰OtherClass
,例如
class AnotherOtherClass
{
private $other;
public function __construct(OtherClass $other)
{
$this->other = $other;
}
public function readData()
{
// proxy to OtherClass::readData()
return $this->other->readData();
}
public function updateUser($username)
{
// add username
}
}
你也可以这样做,但闻起来很糟糕
class AnotherOtherClass extends OtherClass
{
public function connect()
{
throw new BadMethodCallException('Not available in ' . __CLASS__);
}