Skip to content

Instantly share code, notes, and snippets.

@cjmling
Last active May 6, 2017 09:39
Show Gist options
  • Save cjmling/20a89594372a7667b5b3004905b9d48a to your computer and use it in GitHub Desktop.
Save cjmling/20a89594372a7667b5b3004905b9d48a to your computer and use it in GitHub Desktop.
PHP OOP Modifier and Inheritance
<?php
class Car {
public $public_parent = 'public parent';
private $private_parent = 'private parent';
protected $protected_parent = 'protected parent';
public function getCarPrivate(){
return $this->private_parent;
}
public function getCarProtected(){
return $this->protected_parent;
}
}
class SportsCar extends Car{
public $public_child = 'public child';
private $private_child = 'private child';
protected $protected_child = 'protected child';
public function getProtectedParent(){
return $this->protected_parent;
}
public function getPrivateParent(){
return $this->private_parent;
}
public function getProtectedChild(){
return $this->protected_child;
}
public function getPrivateChild(){
return $this->private_child;
}
}
$sports_car = new SportsCar();
//echo $sports_car->public_child; //OK
//echo $sports_car->private_child; //Exception Error: can not access
//echo $sports_car->protected_child; //Exception Error: can not access
//echo $sports_car->public_parent; //OK
//echo $sports_car->private_parent; //Error undefined
//echo $sports_car->protected_parent; //Exception Error Can not access
//echo $sports_car->getProtectedChild(); //OK
//echo $sports_car->getPrivateChild(); //OK
//echo $sports_car->getProtectedParent(); //OK
//echo $sports_car->getPrivateParent(); //Error Undefined on line return $this->private_parent;
//echo $sports_car->getCarPrivate(); //OK
//echo $sports_car->getCarProtected(); //OK
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment