我从未见过属性和方法是私有(private)的或 protected 单一特征。
每次我处理特征时,我都观察到声明到任何特征中的所有属性和方法总是只公开的。
特征是否也可以具有私有(private)和 protected 可见性的属性和方法?如果是,如何在类内/其他特征内访问它们?如果不是,为什么?
trait 中可以定义/声明构造函数和析构函数吗?如果是,如何在类里面访问它们?如果不是,为什么?
特征是否可以有常量,我的意思是像具有不同可见性的类常量?如果是,如何进入一个类(class)/其他一些特征?如果不是,为什么?
特别注意:请用适当的例子来证明这些概念来回答问题。
最佳答案
Traits 也可以拥有具有私有(private)和 protected 可见性的属性和方法。您可以访问它们,就像它们属于类本身一样。没有区别。
Traits 可以有构造函数和析构函数,但它们不是针对 trait 本身,而是针对使用该 trait 的类。
特性不能有常量。在 7.1.0 版本之前的 PHP 中没有私有(private)或 protected 常量。
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();
关于php - 特征是否可以具有具有私有(private)和 protected 可见性的属性和方法?特征可以有构造函数、析构函数和类常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47727003/