简体   繁体   English

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

[英]Can traits have properties & methods with private & protected visibility? Can traits have constructor, destructor & class-constants?

I've never seen a single trait where properties and methods are private or protected. 我从未见过属性和方法是私有或受保护的单一特征。

Every time I worked with traits I observed that all the properties and methods declared into any trait are always public only. 每次我使用特征时,我都会发现声明为任何特征的所有属性和方法都是公共的。

Can traits have properties and methods with private and protected visibility too? 特征是否也具有私有和受保护可见性的属性和方法? If yes, how to access them inside a class/inside some other trait? 如果是,如何在类/内部其他特征内访问它们? If no, why? 如果不是,为什么?

Can traits have constructor and destructor defined/declared within them? 特征是否可以在其中定义/声明构造函数和析构函数? If yes, how to access them inside a class? 如果是,如何在课堂内访问它们? If no, why? 如果不是,为什么?

Can traits have constants, I mean like class constants with different visibility? 特征可以有常量吗,我的意思是像具有不同可见性的类常量? If yes, how to inside a class/inside some other trait? 如果是的话,如何在课堂内/其他特质内? If no, why? 如果不是,为什么?

Special Note : Please answer the question with working suitable examples demonstrating these concepts. 特别提示:请通过展示这些概念的适当实例回答问题。

Traits can have properties and methods with private and protected visibility too. 特征也可以具有私有和受保护可见性的属性和方法。 You can access them like they belong to class itself. 您可以访问它们,就像它们属于类本身一样。 There is no difference. 没有区别。

Traits can have a constructor and destructor but they are not for the trait itself, they are for the class which uses the trait. 特征可以有构造函数和析构函数,但它们不适用于特征本身,它们适用于使用特征的类。

Traits cannot have constants. 特征不能有常数。 There is no private or protected constants in PHP before version 7.1.0. 在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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM