PHP Classes
Classes are the cookie-cutters / templates that are used to define objects.
Classes, Class Properties and Class Methods
To define a class:
1 2 |
class person{ } |
Variables in classes are called properties:
1 |
var $name; |
Define properties with access modifiers (public, protected and private)
1 2 3 4 5 6 7 8 |
/* public properties have no access restrictions, meaning anyone can access them*/ public $height; /* protected properties can only be accessed by the same class and classes derived from the original class */ protected $social_insurance; /* private properties can only be accessed by the class it is in*/ private $pinn_number; |
Methods
Functions in classes are called methods and are used to manipulate the classes own data / properties:
1 2 3 4 5 6 |
function get_name() { return $this->name; } function set_name($new_name) { $this->name = $new_name; } |
The current object is called with $this
A property of the object is called with $this->name
1 |
$this->name |
Get/Set Conventions
Use the naming convention “get_name” for method names that get a data value.
Use the naming convention “set_name” for method names that set a data value.
Creating Class Objects and Storing and Retrieving Class Object Properties
Create a class object with the ‘new’ keyword.
1 |
$stefan = new person(); |
Set an objects properties using the methods (the setters) we created.
1 |
$stefan->set_name("Stefan Mischook"); |
Get an objects properties using the methods (the getters) we created.
1 |
echo "Stefan's full name: " . $stefan->get_name(); |
Constructors
Objects can have a special built-in method called a ‘constructor’. Constructors allow you to initialise your object’s properties when you create an object. If you optionally create a __construct() function PHP will automatically call the __construct() method/function when you create an object from your class.
Populate the constructor method with its arguments by providing a list of arguments after the class name like you would with a function.
1 |
$stefan = new person("Stefan Mischook"); |
Class Inheritance
Inheritance is a fundamental capability/construct in OOP where you can use one class, as the base/basis for another class … or many other classes. Use the keyword ‘extends’ to link the inheritance.
1 2 3 4 5 |
class employee extends person{ function __construct($employee_name) { $this->set_name($employee_name); } } |
Overriding methods
Declare the same method name in the child class to override its parent class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class person{ protected function set_name($new_name) { if ($new_name != "Jimmy Two Guns") { $this->name = strtoupper($new_name); } } } class employee extends person{ protected function set_name($new_name) { if ($new_name == "Stefan Sucks") { $this->name = $new_name; } } } |
Check out https://www.killerphp.com/tutorials/php-objects-page-1/ for more details on PHP classes.
Recent Comments