CodeToLive

PHP Object-Oriented Programming

Class and Object


<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}

$apple = new Fruit();
$apple->set_name('Apple');
echo $apple->get_name();
?>
      

Constructor


<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
}

$apple = new Fruit("Apple", "red");
?>
      

Inheritance


<?php
class Fruit {
  public $name;
  public $color;
  public function intro() {
    echo "The fruit is {$this->name}";
  }
}

class Strawberry extends Fruit {
  public function message() {
    echo "Am I a fruit or a berry? ";
  }
}

$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
      
Back to Tutorials