PHP/Class/Getter Setter

Материал из Web эксперт
Перейти к: навигация, поиск

Call getter to get value for property

   <source lang="html4strict">

<?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}";
   }

} $product1 = new Employee("B", "B1", "B2", 5.99 ); $product2 = new Employee("A", "A1", "A2", 10.99 ); print "author: ".$product1->getFullName()."\n"; print "artist: ".$product2->getFullName()."\n"; ?>


      </source>
   
  


Define and call getter method

   <source lang="html4strict">

<?php

  class Staff
  {
     var $name;
     var $city;
     protected $wage;
     function __get($propName)
     {
        echo "__get called!
"; $vars = array("name","city"); if (in_array($propName, $vars)) { return $this->$propName; } else { return "No such variable!"; } } } $employee = new Staff(); $employee->name = "Joe"; echo $employee->name."
"; echo $employee->age;

?>

      </source>
   
  


Define getter and setter

   <source lang="html4strict">

<?php

  class Staff {
     private $name;
     // Getter
     public function getName() {
        return $this->name;
     }
     // Setter
     public function setName($name) {
        $this->name = $name;
     }
  }

?>

      </source>