Zend PHP 7 Certification – OOP – Instantiation

This post covers the Instantiation section of the OOP chapter when studying for the Zend PHP 7 Certification.

Object-oriented programming is a style of coding that allows developers to group similar tasks into classes. This allows code to be easily maintained and you can re-use code from classes without the need of duplication.

Objects can be created by using the new statement which will instantiate a new class.

<?php
class MyClass {

}

$object = new MyClass();

An object will always be created unless the object has a constructor defined that throws an exception on error.

To instantiate an empty generic PHP object, you can simply write: $object = new stdClass().

You can also cerate stdClass objects with some properties and values by casting an array as an object.

<?php
  $object = (object) [
    'propertyOne' => 'foo',
    'propertyTwo' => 42,
  ];

A class is a template in which objects are made. Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

If the class is in a namespace, its fully qualified name must be used when doing this.

<?php
namespace somenamespace;
class MyClass {
    function foo() {
        return __FUNCTION__;
    }
}

$class = new \somenamespace\MyClass;
echo $class->foo(); // Outputs: foo

The class name can be any valid label, provided it is not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

<?php
class MyClass {

}

In PHP 7 there are a few ways to create an empty object.

$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}

$obj1 and $obj3 are the same type, but they are not identical (i.e. $obj1 !== $obj3).

All three objects will output a simple JS object, {}, using json_encode().

echo json_encode([
    new \stdClass,
    new class{},
    (object)[],
]);

// Outputs: [{},{},{}]

Objects can be converted into strings using the __toString() magic method.

class MyObject {
    public function __toString() {
        return "Testing";
    }
}

$obj = new MyObject;

echo $obj; // Outputs: Testing

An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible). An object’s __clone() method cannot be called directly.

$copy_of_object = clone $object;

Should you need to store an object’s data, the serialize() function gives you the ability to do so.

When serialising objects, PHP will attempt to call the member function __sleep() prior to serialisation. This is to allow the object to do any last minute clean-up, etc. prior to being serialised.

<?php
class MyObject {
}

$obj = new MyObject();
echo serialize($obj); // Outputs: O:8:"MyObject":0:{}
<?php
class MyObject {
    public $integer = 3;
}

$obj = new MyObject();
echo serialize($obj); // Outputs: O:8:"MyObject":1:{s:7:"integer";i:3;}

The anatomy of a serialised value is described below.

  • String – s:size:value;
  • Integer – i:value;
  • Boolean – b:value; (does not store “true” or “false”, does store ‘1’ or ‘0’)
  • Null – N;
  • Array – a:size:{key definition;value definition;(repeated per element)}
  • Object – O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}

Likewise, unserialize() will restore the object, and __wakeup() will attempt to be called.

A class may contain its own constants, variables (called “properties”), and functions (called “methods”).

<?php
class MyClass
{
    // Property declaration
    public $var = 'a default value';

    // Method declaration
    public function displayVar() {
        echo $this->var;
    }
}

$class = new MyClass();
$class->displayVar();   // Prints out 'a default value'

You may notice the use of the $this keyword. The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object.

View the other sections:

Note: This article is based on PHP version 7.0.