zoukankan      html  css  js  c++  java
  • PHP Trait特性

    php类的单继承性,无法同时从两个基类中继承属性和方法,为了解决这个问题,使用Trait特性解决.

    Trait是一种代码复用技术,为PHP的单继承限制提供了一套灵活的代码复用机制.

    用法:通过在类中使用use 关键字,声明要组合的Trait名称,具体的Trait的声明使用Trait关键词.  注意:Trait不能实例化

    demo示例:

     1 <?php
     2 trait Dog{
     3     public function dog(){
     4     echo 'This trair dog';
     5     }
     6 }
     7 
     8 trait Fish{
     9     public function fish(){
    10     echo 'This trair fish';
    11     }
    12 }
    13 
    14 
    15 class Animal{
    16     public function name(){
    17         echo 'This is animal';
    18     }
    19 }
    20 
    21 class Cat extends Animal{
    22     use Dog,Fish;
    23     public function eat(){
    24         echo 'This is animal cat eat';
    25     }
    26 }
    27 
    28 $data = new Cat();
    29 $data->name();//This is animal
    30 echo '<pre>';
    31 $data->eat();//This is animal cat eat
    32 echo '<pre>';
    33 $data->dog();//This trair dog
    34 echo '<pre>';
    35 $data->fish();//This trair fish

    结果打印:

  • 相关阅读:
    [Effective C++]条款01:视C++为一个语言联邦
    DOTNET
    simulation
    掩码
    motorsimsrc
    Unprivileged User's Account
    LAN WAN
    calloc malloc realloc
    useradd
    change user ID and group ID
  • 原文地址:https://www.cnblogs.com/cxx8181602/p/9815669.html
Copyright © 2011-2022 走看看