PHP Object Oriented Programming Cheatsheet

Basics concepts:

  • Classes contain your code logically and functionally organized. Inside classes functions are called methods and variables become properties.
  • An object is an instance of a class. It is instantiated with the keyword 'new': 
$example_object = new exampleClass($variable1, $variable2);

Variables can be passed during the object instantiation and they will be processed as arguments for the __construct() method.
  • __construct() is a magic method which is always executed when a class is instantiated. Similarly __destruct() is called when the class has finished i.e. when the script finishes. 
  • Inheritance means that a class can access and use all of the properties and methods of the parent class unless otherwise specified. To inherit a child class simply extends a parent:
class childClass extends parentClass

  • Abstract class or method cannot be directly used. Instead it should be extended(for classes) or redefined(for methods). Abstract items are to be used as model or basic design. If a method is defined as abstract it must be included in the child classes.
  • Final class cannot be extended. Final methods cannot be overriden in its child classes.
  • Autoloading - PHP has a very useful function called __autoload which is executed always when instantiating a new object. It can be very useful if your classes are in different files and you want to load them automatically. For example:
function __autoload($className) {
    include 'includes/$className . '.php';

$obj  = new testClass(); 

This will first include the file includes/testClass.php and then instantiate the class.
  • The difference between private and protected properties is that private properties can be accessed only by the class itself. On the other hand protected can be accessed from child classes too. Neither can be accessed from outside.
  • A class static property or method can be accessed even without instantiating the class:
echo someClass::$static_property;

  • Difference between :: and when ->
In simple words when you have instantiated an object you will be using ->. Otherwise you will be referring directly to the class and :: has to be used.

Similarly self:: and this-> are used when referring direct to classes or instantiated ones.

blog comments powered by Disqus