PHP Classes
HomeHTAJScriptJavaScriptPHP

The following is an example of how classes can be defined in PHP:

Class Building
{
	var $name;
	var $floors;
	
	function Building($name, $floors)
	{
		$this->name = $name;
		$this->floors = $floors;
	}
	
	function setName($newName)
	{
		$this->name = $newName;
	}
	
	function getName()
	{
		return $this->name;
	}
	
	function getFloors()
	{
		return $this->floors;
	}
	
	function toString()
	{
		if(($floors = $this->getFloors()) == 1)
			$floors = "$floors floor";
		else
			$floors = "$floors floors";
		return "<p>Building is named \"" . $this->getName() . "\" and has $floors.</p>";
	}
}

Class House extends Building
{
	var $owner = "";
	var $basement;
	
	function House($name, $floors, $owner)
	{
		parent::Building($name, $floors);
		$this->setOwner($owner);
	}
	
	function setOwner($owner)
	{
		$this->owner = $owner;
	}
	
	function getOwner()
	{
		return $this->owner;
	}
	
	function toString()
	{
		// Define the text stating how many floors there are.
		if(($floors = $this->getFloors(false)) == 1)
			$floors = "$floors floor";
		else
			$floors = "$floors floors";

		// Define $owner.
		if(strlen($owner = $this->getOwner()) == 0)
			$owner = "nobody";

		return "<p>House is named \"" . $this->getName() . "\", has $floors, and"
			. " is owned by $owner.</p>";
	}
}

// Define the Empire State Building.
$b = new Building("Empire State Building", 102);
echo $b->toString();

// The following line would cause an error.
//$b->setName("Empire State Building #2");

// Define the Smart House.
$h = new House("Smart House", 2, "");
echo $h->toString();

// Give the smart house an owner.
$h->setOwner("Arnold Bagwell");
echo $h->toString();

// Give the house a new owner.
$h->setOwner("Carol and David Ernest");
echo $h->toString();

The above code produced the following results:

Building is named "Empire State Building" and has 102 floors.

House is named "Smart House", has 2 floors, and is owned by nobody.

House is named "Smart House", has 2 floors, and is owned by Arnold Bagwell.

House is named "Smart House", has 2 floors, and is owned by Carol and David Ernest.