Access properties : Class Method « Class « PHP






Access properties

 
<?php
 
  class Bird
  {
    function __construct($name='No-name', $breed='unknown', $price = 15)
    {
      $this->name = $name;
      $this->breed = $breed;
      $this->price = $price;
    }    
    
    function setName($name)
    {
      $this->name = $name;
    }    
    
    function setBreed($breed)
    {
      $this->breed = $breed;
    }    
    
    function setPrice($price)
    {
      $this->price = $price < 0 ? 0 : $price;
    }
    
    function getName()
    {
      return $this->name;
    }    
    
    function getBreed()
    {
      return $this->breed;
    }    
    
    function getPrice()
    {
      return $this->price;
    }

    function display()
    {
      printf("<p>%s is a %s, and costs \$%.2f.</p>\n", 
              $this->name, $this->breed, $this->price);
    }
  }
  
  $magpie = new Bird('Malaysia', 'magpie', 7.5);

  $magpie->display();
  
  $magpie->setPrice(-14.95);

  $magpie->display();
  
  $magpie->price = -14.95;
  
  $magpie->display();
?>
  
  








Related examples in the same category

1.Pass class instance as parameter
2.Call class methods directly
3.Accessing the Attributes of a Class by Using Functions
4.A Class with a Method
5.Accessing a Property from Within a Method
6.A Class with a Method
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)