gongzhonghao.png
扫码关注我们
最新赞助活动温馨提示:自愿赞助服务器费用,学生和没有工作的整站资源免费下载!
头像

php trait 类方法的静态成员、抽象成员、属性代码教程

来源:http://erdangjiade.com/topic/2349.html 你好,世界。 2017-09-25 22:42浏览(11)

Trait 的抽象成员

为了对使用的类施加强制要求,trait 支持抽象方法的使用。

表示通过抽象方法来进行强制要求的例子

<?php
trait Hello {
    public function sayHelloWorld() {
        echo 'Hello'.$this->getWorld();
    }
    abstract public function getWorld();
}
class MyHelloWorld {
    private $world;
    use Hello;
    public function getWorld() {
        return $this->world;
    }
    public function setWorld($val) {
        $this->world = $val;
    }
}
?>

Trait 的静态成员

Traits 可以被静态成员静态方法定义。

静态变量的例子

<?php
trait Counter {
    public function inc() {
        static $c = 0;
        $c = $c + 1;
        echo "$c
";
    }
}
class C1 {
    use Counter;
}
class C2 {
    use Counter;
}
$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

静态方法的例子

<?php
trait StaticExample {
    public static function doSomething() {
        return 'Doing something';
    }
}
class Example {
    use StaticExample;
}
Example::doSomething();
?>

静态变量和静态方法的例子

<?php
trait Counter {
    public static $c = 0;
    public static function inc() {
        self::$c = self::$c + 1;
        echo self::$c . "
";
    }
}
class C1 {
    use Counter;
}
class C2 {
    use Counter;
}
C1::inc(); // echo 1
C2::inc(); // echo 1
?>

属性

Trait 同样可以定义属性。

定义属性的例子

<?php
trait PropertiesTrait {
    public $x = 1;
}

class PropertiesExample {
    use PropertiesTrait;
}

$example = new PropertiesExample;
$example->x;
?>

如果 trait 定义了一个属性,那类将不能定义同样名称的属性,否则会产生一个错误。如果该属性在类中的定义与在 trait 中的定义兼容(同样的可见性和初始值)则错误的级别是 E_STRICT,否则是一个致命错误。

冲突的例子

<?php
trait PropertiesTrait {
    public $same = true;
    public $different = false;
}

class PropertiesExample {
    use PropertiesTrait;
    public $same = true; // Strict Standards
    public $different = true; // 致命错误
}
?>

Use的不同

不同use的例子

<?php
namespace FooBar;
use FooTest;  // means FooTest - the initial  is optional
?>
<?php
namespace FooBar;
class SomeClass {
    use FooTest;   // means FooBarFooTest
}
?>

第一个use是用于 namespace 的 use FooTest,找到的是 FooTest,第二个 use 是使用一个trait,找到的是FooBarFooTest。

以上就是php trait 的静态成员、抽象成员、属性代码详解的详细内容,更多请关注二当家的素材网其它相关文章!

评论0
头像

友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群

1 2