Define Protected member in PHP

Description

The following code shows how to define Protected member.

Example


/*  www.  j a  va  2s .  c om*/
<?php
  class Widget
  {
    private $name;
    private $price;
    private $id;

    public function __construct($name, $price)
    {
      $this->name = $name;
      $this->price = floatval($price);
      $this->id = uniqid();
    }

    //checks if two widgets are the same
    public function equals($widget)
    {
      return(($this->name == $widget->name) AND
      ($this->price == $widget->price));
    }

    protected function getName()
    {
      return($this->name);
    }
  }

  class Thing extends Widget
  {
    private $color;

    public function setColor($color)
    {
      $this->color = $color;
    }

    public function getColor()
    {
      return($this->color);
    }

    public function getName()
    {
      return(parent::getName());
    }
  }

  $w1 = new Widget('Cog', 5.00);
  $w2 = new Thing('Cog', 5.00);
  $w2->setColor('Yellow');

  //TRUE (still!)
  if($w1->equals($w2))
  {
    print("w1 and w2 are the same<br>\n");
  }

  //print Cog
  print($w2->getName());
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition