Object Oriented Programming – PHP Certification Exam Series [8]


PHP OOP - PHP Certification Exam

Introduction: This is the eighth part of my study notes for the Zend PHP Certification Exam. You can read more about my PHP Certification exam journey here.

Basics

  • Slower than procedural code, but allows complex tasks to be understood more readily
  • Objects are now dealt with by reference rather than by value, objects must be explicitly cloned to be copied
  • Properties and methods of a class are called members
  • A PHP reference is an alias, which allows two different variables to write to the same value. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
  • Static functions can only access static properties of the class
  • get_object_vars ( $object ) / get_class_vars ( $class ) – gets the accessible non-static properties of the given object according to scope in an array
  • get_class_methods ( $class ) – Returns an array of method names defined for the class specified by $class, if called from outside, returns only public methods
  • forward_static_call_array ( $function,$array )  – calls a user defined function or method given by the function parameter, can’t be used outside a class, uses late static binding
  • class_alias ($original,$alias) – create alias for classes and interfaces
  • Class – the container for a number of contents, properties and methods, class names must begin with _ or letter (uppercase by convention); It’s now possible to reference the class using a variable (e.g., echo $classname::constant;). The variable’s value can not be a keyword.
class A {
   function foo(){
      if (isset($this)) {
         echo '$this is defined ('.get_class($this).")\n";
      }
   }
}
  • Abstract – classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must be defined as abstract; when a class extends an abstract class, all the abstract methods must be declared before instantiation, the visibility must be equal or less restricted than the abstract class
abstract class A {
   abstract private function foo();
}
  • Interface – just specifies the names of methods a class must have; all methods must be public; use the keyword implements, can implements more than 1 interface (but the interfaces should not have the same method names); interface constants cannot be overwritten by the class implementing the
interface A extends B,C {  // interfaces can extend more than 1 interfaces
   public function foo($var);
   public function foo2($var,$var2);
}
  • However if B,C carries methods with the same name, a fatal error will result.
  • Traits – (from PHP 5.4) a Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way; Trait methods/properties will overwrite parent methods/properties, but methods/properties from the current class will overwrite the trait;
trait traitExample {
   function a() { … }
}
class A {
   use traitExample, traitExample2;  // should not have same method names, otherwise use 'as' for conflict resolutions
   ...
}
  • new – to create an instance of a class, classes must be defined before instantiation; if the class has a constructor that throw an error, the object will NOT be created
$instance = new A(); // variable name allowed e.g. $class='A';… new $class()…
$instance_b = new $instance; // allowed from PHP 5.3
  • extends – inherit the public and protected methods and properties, a class can only extend from 1 class only; if a class extends another, then the parent class must be declared before the child class structure; the child class must have a visibility equal or less strict than the parent class; the parameter signature cannot be “stricter” than before or an E_STRICT error will be thrown (except constructor); it is possible to access the overridden methods or static properties by referencing them with parent::
class ExtendClass extends BaseClass {
   echo "This class is extended";
   parent::displayVar();
}
  • clone – to create a copy of the object; any properties that are references to other variables, will remain references; __clone() method will be called once the object is cloned;
$copy = clone $object;

Properties (class variables)

  • public – can be accessed externally
  • private – private to that particular class and cannot be accessed externally or through extend, accessing private or protected properties will result in fatal error (except from objects of the same type), use getter and setter functions instead
  • protected – private but can also be accessed by extending classes, accessed from outside will result in fatal error
  • var – considered as public (backward compatible with PHP4)
  • Properties must contain scalar or array information and are accessed using the arrow operator -> if the object is instantiated first
public $var1 = myConstant;
public $var2 = array(true, false);
public $var3 = <<<'EOD'  // nowdoc is allowed only in PHP 5.3.0 and later
hello world
EOD;
  • static – must be accessed by the :: method without the need for object instantiation, cannot be accessed using the arrow operator ->, can be array
class MyClass{
   public static $myPro = 12343;
}
print MyClass::$myPro;
  • const – class constant that cannot be changed once defined, accessed by scope resolution operator (::) method without the need for object instantiation first, have a global scope, cannot be altered, cannot be array
const myConstant = 'constant value';

Methods (class functions)

  • Public – can be accessed externally
  • Private – is private to that class and can not be accessed externally, accessing private or protected methods directly (except from objects of the same type) will result in fatal errors
  • Protected – is private and can also be accessed by extending classes, access from outside will result in fatal errors
  • Final – can not be overridden by extending classes, result in fatal errors if overwritten, e.g. final public function a( ){…};
  • __construct() – declare constructor methods for classes, from PHP 5.3.3 namespaced method with the same name of the class will NOT be treated as constructor, but doesn’t affect non-namespaced behavior!!
  • __destruct() – declare destructor methods for classes, called when no other references to the object (all unset() or = NULL), e.g. to close file stream at the destruction of the object

Property Overloading (must be declared public)

  • __set($name,$value) – is automatically run when the inaccessible properties (either protected,private or not existent) are being written to: public function __set($name,$value){$this->data[$name] = $value;}
  • __get($name) – is automatically run when the inaccessible properties are being read
  • __isset($name) – is automatically run when the isset() or empty() is called to inaccessible properties
  • __unset($name) – is automatically run when the unset() is called to inaccessible properties

Method Overloading (must be declared public)

  • __call($name,$arguments) – is triggered when invoking inaccessible methods in an object context
  • __callStatic($name,$arguments) – is triggered when invoking inaccessible methods in a static context
  • An E_WARNING level error is issued if the magic overloading methods are declared static (should be public)

Magic Methods

  • __sleep() – if serialize() is call on the object, the __sleep() method will be called to output an array of all key/value pairs for serialization
  • __wakeup() – if unserialize() is call on the object, the __wakeup() method will try to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks; when unserialize to an object, the class definition must also be included in all pages of the application, not doing so will result in giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object useless
  • __toString() – allows a class to decide how it will react when it is treated like a string, e.g. echo $obj; cannot throw exception otherwise fatal error would result
  • __invoke($arg) – method is called when a script tries to call an object as a function, e.g. is_callable($obj);
  • static __set_state($properties) – this static method is called for classes exported by var_export() 

Comparing Objects

  • obj1 == obj2 equal if they have the same attributes and values, and are instances of the same class
  • obj1 === obj2 object variables are identical if and only if they refer to the same instance of the same class

Typehinting

  • Functions are now able to force parameters to be objects, interfaces, arrays or callable (since PHP 5.4). However, if NULL is used as the default parameter value (i.e. $obj = NULL), NULL is also allowed other than the type hint
  • Cannot be used on integers/string, e.g. function(string $a) // error will be thrown
  • If class or interface is specified as type hint then all its children or implementations are allowed too.
  • Failing to satisfy the type hint results in a catchable fatal error
function test(stdClass $obj = NULL) { … }
test(NULL);
test(new stdClass);

Late Static Bindings

  • Late static bindings tries to solve that limitation of static binding (by reference function of the same class) by introducing a keyword (static::) that references the class that was initially called at runtime.
  • Late static bindings’ resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.
  • Used for retrieving the caller class information when static call to inherited method is made, so there’s no object available to carry the class info
class A {
   public static function who() {
      echo __CLASS__;
   }
   public static function test() {
      static::who(); // Here comes Late Static Bindings
   }
}

class B extends A {
   public static function who() {
      echo __CLASS__;
   }
}

B::test(); // gives B; if self is used, gives A

Instanceof / is_a()

  • instanceof: as a language construct, allows you to inspect all of the ancestor classes of your object, as well as any interfaces
  • is_a(): as a function e.g. is_a($object,’class’);

Object Iteration

  • PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible (i.e. public) properties will be used for the iteration.
  • May use the Iterator Interface or IteratorAggregate Interface for implementing iteration.
class MyClass
{
   public $var1 = 'value 1';
   protected $protected = 'protected var';
   private $private   = 'private var';
}

$class = new MyClass();
foreach($class as $key => $value) {
   print "$key => $value\n";  // output var 1=> value 1
}

Exceptions

  • Unified method of error handling, using a OOP approach (as opposed to the internal error reporting mechanism)
  • Can be accomplished with try … catch blocks (from PHP 5.4 – finally) or by setting a unified error handler using set_exception_handler()
try {
   $o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {      // Doesn't match this type
   echo "Caught my exception\n", $e;
   $e->customFunction();
} catch (Exception $e) {        // Will be caught
   echo "Caught Default Exception\n", $e;
}
  • Errors can be simply translated to exceptions with ErrorException class
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
   throw new ErrorException($errstr, $errno, 0, $errfile, $errline); //0:severity
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
  • The thrown object must be an instance of the Exception class or a subclass of Exception; trying to throw an object that is not will result in a PHP Fatal Error; All unhandled exceptions are fatal
  • The Standard PHP Library (SPL) provides a good number of built-in exceptions.
  • set_exception_handler ( callback $exception_handler ) sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called. Returns the name of the previously defined exception handler, or NULL on error.
  • restore_exception_handler ( ) to revert to the previous exception handler
Exception {
   /* Properties */
   protected string $message ;
   protected int $code ;
   protected string $file ;
   protected int $line ;
   /* Methods */
   public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
   final public string getMessage ( void ) // get error message
   final public Exception getPrevious ( void ) // previous error
   final public mixed getCode ( void ) // get error code
   final public string getFile ( void ) // get filename
   final public int getLine ( void ) // get the line
   final public array getTrace ( void ) // get the stack trace (array with all)
   final public string getTraceAsString ( void ) // stack trace as string
   public string __toString ( void ) // when echo $e used
   final private void __clone ( void ) // fatal error
}

Generators (only in PHP > 5.5)

  • Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface
  • A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over
  • use the yield keyword

Predefined Interfaces

  • Traversable – Interface to detect if a class is traversable using foreach, must be implemented by either IteratorAggregate or Iterator
  • Iterator – Interface for external iterators or objects that can be iterated themselves internally (i.e. turning the object into an iterator), a number of iterators are predefined in SPL, e.g. to define it’s own iteration details
  • IteratorAggregate – Interface to create an external Iterator, e.g. to use foreach or ArrayIterator
  • ArrayAccess – Interface to provide accessing objects as arrays.
  • Serializable – Interface for customized serializing. Classes that implement this interface no longer support __sleep() and __wakeup().
  • Closure – Class used to represent anonymous functions.

Reflection

  • a complete reflection API that adds the ability to reverse-engineer of objects, classes, methods, properties, functions, parameters, exceptions, extensions
  • e.g. ReflectionClass, ReflectionFunction, ReflectionObject, ReflectionMethod, ReflectionProperty, ReflectionException
$obj = new ReflectionFunction('strstr');
foreach( $obj->getParameters() as $param ){
   print $param;
} // output: Parameter #0 [ $haystack ] Parameter #1 [ $needle ]

SPL

  • Standard PHP Library, a collection of interfaces and classes that are meant to solve standard problems.
  • ArrayIterator – When you want to iterate over the same array multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that refer to it either by using foreach or by calling its getIterator() method manually.
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu');
$object = new ArrayIterator($array);
for ( $object->rewind(); $object->valid(); $object->next() )
{
   if($object->current() === 'kiwi')
   {
      $object->offsetUnset( $object->key() );
   }
   echo $object->key().' - '.$object->offsetGet($object->key())."\n";
}
  • ArrayObject – This class allows objects to work as arrays.
Flags: ArrayObject::STD_PROP_LIST, ArrayObject::ARRAY_AS_PROPS
class Example {
   public $public = 'prop:public';
   private $prv   = 'prop:private';
   protected $prt = 'prop:protected';
}
$arrayobj = new ArrayObject(new Example());
var_dump($arrayobj->count()); // int(1), only public properties
$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();
while($iterator->valid()) {
   echo $iterator->key() . ' => ' . $iterator->current() . "\n";
   $iterator->next();
}
  • SPLObjectStorage – a map from objects to data or, by ignoring data, an object set
  • Interfaces
  • Countable – Classes implementing Countable can be used with the count() function
  • OuterIterator – iterate over iterators
  • SeekableIterator – seeking to a position
  • RecursiveIterator – iterates recursively
  • Functions
  • class_implements($class) – Return the interfaces which are implemented by the given class
  • class_parents($class) – Return the parent classes of the given class

SPL Autoload

  • __autoload – can be used to include any necessary class automatically on instantiation, from PHP 5.3 exceptions thrown in the __autoload function can be caught in the catch block
<?php
function __autoload($class_name)
{
   require_once "/www/phpClasses/{$class_name}.inc.php";
}
$a = new friend;
  • call spl_autoloader_register($function,$throw,$prepend) to register a function for autoloading; $throw (throw error) and $prepend (in the load stack) accepts TRUE or FALSE;
  • void spl_autoload ( string $class_name [, string $file_extensions = spl_autoload_extensions() ] ) the default implementation for __autoload( ), i.e. call to __autoload will invoke this function
  • string spl_autoload_extensions ([ string $file_extensions ] )
  • bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) – first call to this function replaces the __autoload() call in the engine with its own implementation

 

 

You can read more about my PHP Certification exam journey here.

GreyCampus PMP online training course bundle for US$149 only

Support website running for FREE, thanks!

If you find this post helpful and if you are thinking of buying from Amazon, please support the running cost of this website at no extra cost to you by searching and buying through the search box below. Thank you very much for your help!

Edward Chung

Edward Chung aspires to become a full-stack web developer and project manager. In the quest to become a more competent professional, Edward studied for and passed the PMP Certification, ITIL v3 Foundation Certification, PMI-ACP Certification and Zend PHP Certification. Edward shares his certification experience and resources here in the hope of helping others who are pursuing these certification exams to achieve exam success.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

2 Responses

  1. Juan Cadima says:

    Hello Edward, first of all, congrats for your website , it packs really good information that im sure is helpful to hundreds of thousand of people (if not millions)

    Im currently studying for the zend php certification which recently added php 7 (200-710), your exam series review is a great resource, i would say more than the official php study guide and some books that i already went over (thumbs up)

    The reason i want to get a php certification is because of the new opportunities it opens, i am also a fan of Laravel and they announced some time ago that they are launching a Laravel Certification https://laravel.com/certification/ , i would like to know what are your thoughts about it, if its worth it or would make little difference if one already has a Zend PHP certification, in my free time im also building new projects with Laravel in hopes that by the time they launch that certification i may take that cert.
    But in your point of view do you think i should focus 100% in getting the Zend PHP cert. first and then getting that other Laravel certification or skip the Zend PHP cert. and go straight to the Laravel one? do you see an added value in that Laravel certification?

    Thank you for your time.

    —–
    Juan

    • Edward Chung says:

      Thanks for your comments.

      Whether a certification is beneficial or not really is a tough question to answer. If you ask me whether I have gained anything directly from getting PHP certification, my answer is NO. However, the process of preparing for the PHP certification really helps me to become better versed in the language and write better apps.

      So, my answer would be: if you have the time and money, do go for both certifications as this would help you become a better coder.

      Wish you success in your career!