php is a single or multiple inheritance to inherit it?

PHP does not support multiple inheritance, multiple inheritance then how to achieve it?

Interface can be used to achieve or trait

interface here we do not do too much explanation, and it is the principle of a class can implement multiple interfaces. The following code will be able to explain.

interface test1{

public function connect();

}

interface test2{

public function contact();

}

// class can implement multiple interfaces at the same time

class myCode implements test1,test2{

public function connect(){

    echo "test1!";

}

public function contact(){

    echo "test2!":

}

}

Here we focus on what trait implement multiple inheritance (in fact, not called multiple inheritance, multiple inheritance should be called similar functions)
What is the trait that it?
A: It looks like both interfaces like a class, actually not, Trait can be seen as part of a class implementation may be mixed with one or more existing PHP class, which has two functions: Indicates what class can do; provide a modular implementation. Trait is a code-multiplexing, provides a flexible mechanism for code reuse single inheritance restriction PHP.
So how to achieve trait it? Look at the code below:

// base class

  class basicTest{

    public function test(){

      echo "hello,world\n";

    }

  }

  //traitOne

  {related traitOne

    public function test(){

      echo "this is trait one";

    }

    public function testOne(){

      echo "one
";

    }

  }

  // traitTwo

  Who traitTwo {

    // public function test(){

      // echo "this is trait two!";

    // }

    public function testTwo(){

      echo "Two
";

    }

  }

  // inherit the base class, and use trait

  class myCode extends basicTest{

    use traitOne, traitTwo;

    public function test(){

      echo "hehaha!!
";

    }

  }

  $obj = new myCode();

  $obj->testTwo();

note:

Priority: own method> trait approach> inherited methods (is like that.)
If we open the note in the above code, will get an error, because the method of the same name in the two trait.

Guess you like

Origin www.cnblogs.com/djwhome/p/12532199.html