Tutorial by Examples

Let's say we have an interface for logging: interface Logger { function log($message); } Now say we have two concrete implementations of the Logger interface: the FileLogger and the ConsoleLogger. class FileLogger implements Logger { public function log($message) { // Append...
Trying to use several traits into one class could result in issues involving conflicting methods. You need to resolve such conflicts manually. For example, let's create this hierarchy: trait MeowTrait { public function say() { print "Meow \n"; } } trait WoofTrait {...
trait Hello { public function sayHello() { echo 'Hello '; } } trait World { public function sayWorld() { echo 'World'; } } class MyHelloWorld { use Hello, World; public function sayExclamationMark() { echo '!'; } } $o = new My...
trait HelloWorld { public function sayHello() { echo 'Hello World!'; } } // Change visibility of sayHello class MyClass1 { use HelloWorld { sayHello as protected; } } // Alias method with changed visibility // sayHello visibility not changed class MyClass2 { u...
PHP only allows single inheritance. In other words, a class can only extend one other class. But what if you need to include something that doesn't belong in the parent class? Prior to PHP 5.4 you would have to get creative, but in 5.4 Traits were introduced. Traits allow you to basically "copy...
Over time, our classes may implement more and more interfaces. When these interfaces have many methods, the total number of methods in our class will become very large. For example, let's suppose that we have two interfaces and a class implementing them: interface Printable { public functio...
Disclaimer: In no way does this example advocate the use of singletons. Singletons are to be used with a lot of care. In PHP there is quite a standard way of implementing a singleton: public class Singleton { private $instance; private function __construct() { }; public function...

Page 1 of 1