Pass class instance as parameter : Class Method « Class « PHP






Pass class instance as parameter

<?php
    class Employee {
        public $title;
        public $lastName;
        public $firstName;
        public $price;
        
        function __construct( $title, $firstName, $mainName, $price ) { 
            $this->title     = $title;
            $this->firstName = $firstName;
            $this->lastName  = $mainName;
            $this->price     = $price;
        }

        function getFullName() {
            return "{$this->firstName}" . " {$this->lastName}";
        }
    }
    
class EmployeeWriter {
    public function write( $shopProduct ) {
        $str  = "{$shopProduct->title}: ";   
        $str .= $shopProduct->getFullName();
        $str .= " ({$shopProduct->price})\n";
        print $str;
    }
}
$product1 = new Employee( "Title", "A", "B", 5.9 );
$writer = new EmployeeWriter();
$writer->write( $product1 );

?>


           
       








Related examples in the same category

1.Call class methods directly
2.Accessing the Attributes of a Class by Using Functions
3.A Class with a Method
4.Accessing a Property from Within a Method
5.A Class with a Method
6.Access properties
7.Calling an Overridden Method (PHP 5 Syntax)
8.Class Member Overloading
9.Class Member and Method Definitions
10.Defining three member functions for Cat
11.Overriding Methods
12.The Method of a Child Class Overriding That of Its Parent (PHP 4 Syntax)