Php,类型演员(向下倾斜)(摆脱扩展课程)

时间:2016-04-12 07:45:57

标签: php

我知道PhP没有类似于类型转换的东西,但我们试一试。我有一个实体:

class Entity extends Base
{
    private $name;

    public function getName()
    {
        return $this->name;
    }

    public function setName($v)
    {
        $this->name = $v;
    }
}

and its Base

abstract class Base
{
    public function save()
    {
    }
}

现在有一个实体:

$e = new Entity();

我可以将它传递给方法:

$this->callMe($e);

private function callMe (Entity $e)
{
    $e->getName(); // OK!
    $e->save();  // !!!!!!!!!!!! I DONT WANT IT
}

问题是,我只想传递Entity本身,并跳过继承的属性。仅仅因为我不想让别人搞乱其他惯例。当然,我可以这样做:

// problem is too many parameters and not tight coupled enough
$this->callMe($e->getName(), $e->getWhatever());

// then no longer type hinting, just a "bag" array
$this->callMe($e->toArray());

换句话说,我想摆脱继承的类。

1 个答案:

答案 0 :(得分:1)

如果您不想授予对某些继承方法的访问权限,只需在基类中将它们设为私有或受保护。