Define class as constructor parameter : Constructor « Class « PHP






Define class as constructor parameter

<?php
class PersonWriter {

    function writeName( Person $p ) {
        print $p->getName()."\n";
    }

    function writeAge( Person $p ) {
        print $p->getAge()."\n";
    }
}

class Person {
    private $writer;

    function __construct( PersonWriter $writer ) {
        $this->writer = $writer;
    }

    function __call( $method, $args ) {
        if ( method_exists( $this->writer, $method ) ) {
            return $this->writer->$method( $this );
        }
    }

    function getName()  { 
        return "Joe"; 
    }
    function getAge() { 
        return 44; 
    }
}

$person= new Person( new PersonWriter() );
$person->writeName();
$person->writeAge();
?>


           
       








Related examples in the same category

1.Instantiate class by calling the constructor
2.Define and use constructor
3.Define Constructor for Class
4.A Class with a Constructor
5.Adding a Constructor to PriceItem
6.Calling the constructor of the parent class
7.Constructors and Destructors
8.Defining an object constructor
9.Creating the Cat constructor
10.Defining object constructors in PHP 4
11.Using the PHP 5 style constructor
12.invoking parent constructors
13.Using Unified Constructors and Destructors
14.Using Default Constructors