PHP如何在子类中禁用特征?

时间:2016-02-15 15:50:29

标签: php laravel

如果我上课:

class_A{
    use SomeTrait;
}

并且

class_B extends class_A{
    //
}

如何禁用特质" SomeTrait"在class_B类?

2 个答案:

答案 0 :(得分:0)

您无法在子类中禁用继承特征。

但是你可以change trait's method visibility

答案 1 :(得分:0)

为什么在使用特征时将类扩展到第一位 - 如果 - *(让我们说它是真的)你的代码/项目中有很多特征......?

class A {
    use private_trait_holding_this,
        private_trait_holding_just_that;

    // .. properties, public methods...
}

class B {
    use private_trait_holding_just_that;

    // ... properties, public methods ....
}

特征是非常强大的东西,我经常喜欢将它们称为bags。正因为如下。请注意,特征内的所有内容都是private

<?php namespace
{
    trait private_properties
    {
      private $path;
      private $file_;
      private $pack_;
    }

    trait private_methods_uno
    {

      private function getFilePrivate()
      {
           if(is_file($this->path))
           $this->file_ = file_get_contents($this->path);
      }

    }

    trait private_methods_due
    {

      private function putFilePrivate()
      {
           if(!is_string($this->file_))
                die('File probably doesn\'t exist ... ');
           else
           {
                $this->pack_ = base64_encode($this->file_);
                file_put_contents(("{$this->path}.bak"), $this->pack_, LOCK_EX);
                $this->pack_ = null; $this->file_ = $this->pack_;
           }
      }

    }

    final class opcodeToString
    {
      use
           private_properties,
           private_methods_uno,
           private_methods_due;

      public function __construct($path)
      {
           $this->path = $path;
           $this->getFilePrivate();
      }

      public function putFile()
      {
           $this->putFilePrivate();
      }

    }



    $filepath = '/my/path/to/opcode.php';
    $ots = new opcodeToString($filepath);
    $ots->putFile();

}