PHP class constants, private, public properties and functions

This is a very simple php class that demonstrates the usage of php class constant, private property, public property, private function and public function.

<?php
class Dog
{
	const KIND = 'Mammal';
	public $name;
	private $dob;

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

	public function speak()
	{
		echo "Woof, I am a ".self::KIND.". My name is $this->name, I am ".$this->calculateAge()." years old.";
	}

	private function calculateAge()
	{
		$currentYear = date('Y');
		return intval($currentYear) - intval(substr($this->dob,0,4));
	}
}

$dog = new Dog("Kimi","2013/03/02");
echo $dog->speak();//Woof, I am a Mammal. My name is Kimi, I am 1 years old.Kimi
echo Dog::KIND;//Mammal
echo $dog::KIND;//Mammal
echo $dog->name;//Kimi
echo $dog->dob;//Fatal error: Cannot access private property Dog::$dob
echo $dog->calculateAge();//Fatal error: Call to private method Dog::calculateAge() from context 
?>
  • PHP constants are declared with the keyword const, it can be access by self::constantName within the class and $ObjectVar::constantName outside the class.
  • PHP private properties can only be accessed within the class by $this->propertyName.
  • PHP public properties can be access within class by $this->propertyName, and $objectVar->propertyName outside the class.
  • PHP private functions can only be accessed within the class by $this->functionName().
  • PHP public functions can be accessed within the class by $this->functionName() and by $objectVar->functionName() outside the class.
  • Search within Codexpedia

    Custom Search

    Search the entire web

    Custom Search