PHP OOP Traits

PHP traits allow using common functionality in multiple classes.

trait data{
	public function msg(){
		echo "Hello, msg method";
	}
}

class First{
	use data;
}

$first= new First();
$first->msg();

PHP OOP Trait method overriding

trait First{
	public function msg(){
		echo "Msg method of first trait <br>";
	}
}

trait Second{
	public function msg(){
		echo "Msg method of second trait <br>";
	}
}

class Person{
	use First, Second{
		First::msg insteadof Second;		
	}
}
$person = new Person();
$person->msg();
© 2016 - 2022, All Rights are Reserved.