Traits Introduction in PHP OOPS

 <?php


// When we want to use some property(of Outside Class) in One class but not in Second
// and Third class at that time we can use trait functionality as shown below :
//For Example, if we want to use some functions in one class but not in second class and
//third class then we can make trait and we can use multiple trait in single
//class as shown below:

//NOTE : we can not inherit multiple class by single class in case of Inheritance but we
//can use multiple trait in single class. This is the difference between Inheritance and
//trait as shown below example.

class Abc {
    public function test() {
        echo "Test from class ABC";
    }
}
trait test {
    public function test1() {
        echo "test1 method of test1 trait <br>";
    }
}

trait test2 {
    public function test2() {
        echo "test2 method of test2 trait <br>";
    }
}

class One extends Abc {
    use test, test2;
}

class Two extends Abc {
    use test, test2;
}

class Three extends Abc {}

class Four extends Abc {}

class Five extends Abc {}

$obj = new One();
$obj->test1();

$obj->test2();

// OUTPUT :
//test1 method of test1 trait
// test2 method of test2 trait

?>

Comments

Popular posts from this blog

GROUP BY Clause and HAVING Clause in PHP

Method Overriding in Traits in PHP

Mysqli database Connection and Display Table Data from Database