特质可以具有属性吗?私人&方法受保护的可见性?特性可以具有构造函数,析构函数&类常量? [英] Can traits have properties & methods with private & protected visibility? Can traits have constructor, destructor & class-constants?

查看:164
本文介绍了特质可以具有属性吗?私人&方法受保护的可见性?特性可以具有构造函数,析构函数&类常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有见过特性和方法是私有或受保护的单个特征.

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.

特征也可以具有具有私有且受保护的可见性的属性和方法吗?如果是,如何在班级内/在其他一些特质内访问它们?如果没有,为什么?

特征可以在其中定义/声明构造函数和析构函数吗?如果是,如何在班级内访问它们?如果没有,为什么?

特征可以具有常量吗,我的意思是像具有不同可见性的类常量一样?如果是的话,如何在一个班级内/在其他一些特质内?如果没有,为什么?

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

推荐答案

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

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.

特质不能具有常量.在PHP 7.1.0之前的版本中,没有私有或受保护的常量.

Traits cannot have constants. There is no private or protected constants in PHP before version 7.1.0.

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();

这篇关于特质可以具有属性吗?私人&amp;方法受保护的可见性?特性可以具有构造函数,析构函数&amp;类常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆