Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在子类中阻止PHP函数_Php_Class_Function - Fatal编程技术网

在子类中阻止PHP函数

在子类中阻止PHP函数,php,class,function,Php,Class,Function,是否可以阻止子类中父类的函数可见性 class DB { function connect() { // connects to db } } class OtherClass extends DB { function readData() { // reads data } } class AnotherOtherClass extends OtherClass { function updateUser($username) { // add u

是否可以阻止子类中父类的函数可见性

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
这可能吗?

听起来好像你实际上不想让另一个类扩展
其他类。也许你想消费/包装/装饰
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__);
    }

更进一步说,我怀疑DB类是否应该首先得到扩展。@Matthew不知道这些类的实际功能,很难调用它如果我使用DB类来处理所有sql操作,那么我可以扩展该类来执行CRUD操作,例如?或者您只是将一个DB类选项传递到CRUD类中以执行数据库操作吗?你会怎么做?@Ourx我会选择后者。您可以将
DB
对象作为依赖项传递,就像在我的回答中
OtherClass
对象是另一个类的依赖项一样