特征是否具有私有和受保护可见性的属性和方法?特征可以有构造函数,析构函数和类常量吗?

6 php constructor visibility traits class-constants

我从未见过属性和方法是私有或受保护的单一特征.

每次我使用特征时,我都会发现声明为任何特征的所有属性和方法都是公共的.

特征是否也具有私有和受保护可见性的属性和方法?如果是,如何在类/内部其他特征内访问它们?如果不是,为什么?

特征是否可以在其中定义/声明构造函数和析构函数?如果是,如何在课堂内访问它们?如果不是,为什么?

特征可以有常量吗,我的意思是像具有不同可见性的类常量?如果是的话,如何在课堂内/其他特质内?如果不是,为什么?

特别提示:请通过展示这些概念的适当实例回答问题.

Hak*_*MEZ 13

特征也可以具有私有和受保护可见性的属性和方法.您可以访问它们,就像它们属于类本身一样.没有区别.

特征可以有构造函数和析构函数,但它们不适用于特征本身,它们适用于使用特征的类.

特征不能有常数.在7.1.0之前的PHP中没有私有或受保护的常量.

trait Singleton{
    //private const CONST1 = 'const1'; //FatalError
    private static $instance = null;
    private $prop = 5;

    private function __construct()
    {
        echo "my private construct<br/>";
    }

    public static function getInstance()
    {
        if(self::$instance === null)
            self::$instance = new static();
        return self::$instance;
    }

    public function setProp($value)
    {
        $this->prop = $value;
    }

    public function getProp()
    {
        return $this->prop;
    }
}

class A
{
    use Singleton;

    private $classProp = 5;

    public function randProp()
    {
        $this->prop = rand(0,100);
    }

    public function writeProp()
    {
        echo $this->prop . "<br/>";
    }
}

//$a1 = new A(); //Fatal Error too private constructor
$a1 = A::getInstance();
$a1->writeProp();
echo $a1->getProp() . "<br/>";
$a1->setProp(10);
$a1->writeProp();
$a1->randProp();
$a1->writeProp();
$a2 = A::getInstance();
$a2->writeProp();
$a2->randProp();
$a2->writeProp();
$a1->writeProp();
Run Code Online (Sandbox Code Playgroud)

  • Trait 常量将在 [PHP 8.2](https://php.watch/versions/8.2/constants-in-traits) 中添加 (6认同)
  • 不,特征不能有常量,请参见[this](/sf/ask/1705058981/) (3认同)