protected //like private but only the subclass can change the values.
public //any code can change this attributes.
private //only method and function can change this data.
class Animal {
protected $name;
protected $favorite_food;
protected $sound;
protected $id;
//Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed.
//In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.
public static $number_of_animals = 0;
const PI = "3.14159"; // never change is value
function getName(){ // encapsulate / protect change the data.
return $this->name; // refers to the current class.
// if there is $name in this function, "this" will refer to the function.
}
// Constructor - initialize things / set some value.
function __construct() {
$this->id = rand(100,1000000); //set a random number between 100 - 1 million.
echo $this->id . " has been assigned<br>";
Animal::$number_of_animals++; //access the static for $number_of_animals .
}
}
Getter and Setters
class Person{
//The name of the person.
private $name;
//The person's date of birth.
private $dateOfBirth;
//Set the person's name.
public function setName($name){
$this->name = $name;
}
//Set the person's date of birth.
public function setDateOfBirth($dateOfBirth){
$this->dateOfBirth = $dateOfBirth;
}
//Get the person's name.
public function getName(){
return $this->name;
}
//Get the person's date of birth.
public function getDateOfBirth(){
return $this->dateOfBirth;
}
//For Override class
function run() {
echo $this->name . " runs<br>";
}
//Set new person
$person = new Person();
//Set the name to "Dov"
$person->setName('Dov');
//Get the person's name.
$name = $person->getName();
//Print it out
echo $name;
//Set person with if statement.
//-----------------------------
//Set the person's name.
public function setName($name){
if(!is_string($name)){
throw new Exception('$name must be a string!');
}
$this->name = $name;
}
Extends / Enarate
class Dog extends Animal {
//We override it on the next code section (on Extends / Enarate).
function run() {
echo $this->name . " runs like crazy<br>"; //we overwrite this function
}