Skip to content

Instantly share code, notes, and snippets.

@joelbrennan0
Created May 15, 2015 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelbrennan0/fc572b85fae2e648cbb7 to your computer and use it in GitHub Desktop.
Save joelbrennan0/fc572b85fae2e648cbb7 to your computer and use it in GitHub Desktop.
Encapsulation within PHP Classes(using getters and setters)
<?php
/*===================================
ENCAPSULATION - protecting our code
===================================*/
//this shows the benefits of encapsulation; ie protecting certain methods and parts of your code from external modification
class Person {
//by declaring our properties private all subsequent methods may only be called from within the class on instantiation.
private $name;
private $age;
//when constructing our person we will take one argument of name. Using this method on a private property we are unable to change after initialization.
public function __construct($name) {
$this->name = $name;
}
//by using a getter we can get the property which is otherwise inaccesible
public function getAge() {
return $this->age;
}
//we are able to update the age using a setter but age must always be over 21. this protects against tricking.
public function setAge($age) {
if ($age < 21) {
throw new Exception("This dude needs to show some ID.", 1);
}
//here we can assign $age in aurgument to $age above.
$this->age = $age;
}
}
$joel = new Person('Joelski the Great');
$joel->setAge(200);
var_dump($joel->getAge());
print_r($joel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment