php-basics-revision [topic-name: traits,static methods and properties]
traits:
php only supported single inheritance , a child class can inherit from one single Parent class ,if we need multiple behaviours from more then one class,traits solve this problem .
trait message1
{
public function msg1()
{
echo "OOP is fun! ";
}
}
trait message2
{
public function msg2()
{
echo "OOP reduces code duplication!";
}
}
class Welcome
{
use message1; //trait-1
}
class Welcome2
{
use message1, message2; // trait-1 and trait-2
}
$obj = new Welcome(); //has access of all methods of only trait-1
$obj2 = new Welcome2(); //has access of all methods of trait-1 and 2
$obj->msg1();
// $obj->msg2();
$obj2->msg1();
$obj2->msg2();
static method:
Static methods can be called directly without creating instance of the class.static methods are declared with the static keyword
class greeting{
public static function welcome(){
echo "hello php";
}
}
greeting::welcome() ;
echo "\n";
calling a static method from another class non-static method
class A
{
public static function welcome()
{
echo "Hello World!";
}
}
class B{
public function msg(){
A::welcome();
}
}
$b = new B() ;
$b->msg() ;
echo "\n";
another example for static method
class domain{
protected static function getWebSiteName(){
return "mhdyhasan.com";
}
}
class domainW3 extends domain{
public $webName ;
public function __construct()
{
$this->webName = parent::getWebSiteName();
}
}
$d = new domainW3() ;
echo $d->webName ;
echo "\n";
example of static properties in class
class pi
{
public static $value = 3.14159;
public function staticValue()
{
return self::$value;
}
}
$pi = new pi();
echo $pi->staticValue();
echo "\n";
example for static properties in child class
class pi{
public static $value = 3.1416 ;
}
class x extends pi{
public function Xstatic(){
return parent::$value ;
}
}
echo x::$value ;
echo "\n";
$v = new x() ;
echo $v->Xstatic();
echo "\n";