Jump to content

include a class within a class


jonniejoejonson

Recommended Posts

You cannot have a class inside a class (nested classes).  However, you can extend a class with another class, and the the object you make from the extended class will inherit the parent class's stuff. Example:

 

<?php
// parent class
class foo {
  var $x;

  function set_x($x) {
    $this->x = $x;
  }

  function get_x() {
    return $this->x;
  }
}

// child class
class bar extends foo {
  var $y;

  // method uses method get_x as if it were its own because it inherited it from foo
  function set_y_to_x() {
    $this->y = $this->get_x();
  }
  
  function echo_y() {
    echo "y : " . $this->y . "<br/>";
  }

  // method uses property $x as if it were its own because it inherited it from foo
  function echo_x() {
    echo "x : " . $this->x . "<br/>";
  }

}

// create an object from class bar
$object = new bar();

// call method from foo because bar inherited it
$object->set_x('blah');

$object->set_y_to_x();
$object->echo_x();
$object->echo_y();

?>

 

output:

x : blah
y : blah

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.