Esquire Theme by Matthew Buchanan
Social icons by Tim van Damme

01

Jun

Quick Syntax intro to Object Oriented Programming (OOP) with PHP

This post is a quick reference from Chapter 6: Objects from “Programming PHP” a book published by O’REILLY and authored by Rasmus Lerdorf, Kevin Tatroe & Peter MacIntyre. It’s the 2nd Edition and it covers PHP5.

Why use Object Oriented Programming (OOP)?

Because it opens the door to cleaner designs, easier maintenance, and greater code re-useability. OOP acknowledges the fundamental connection between data and the code that works on that data, and it lets you design and implement programs around that connection. In a procedural programming language, each user would be a data structure, and there would probably be a set of functions that work with users’ data structures. In a object oriented programming language, each user would be an object—a data structure with attached code. The data and the code are still there, but they are treated as an inseparable unit. The object, as union of code and data, is the modular unit for application development and code reuse.

What is an object?

An object is an instance of a class. In this case, it’s an actual user data structure with attached code. Objects and classes are a bit like values and data types. There is only one integer data type, but there are many possible integers. Similarly, your program defines only one user class but can create many different (or identical) users from it. The data associated with an object are called its properties. The functions associated with an object are called its methods. When you define a class, you define the names of its properties and give the code for its methods.

How to create an object?

$object = new Class;

How to access properties and methods?

$object->propertyName;

$object->methodName(arg1, arg2…);

HTML::p(“Hello, world”); // this is how to access a static method

How to declare a class, a property and a method?

class className [ extends baseclass ] {

     $propertyName = value;

     function methodName(args) { // code }

}

How to declare constants?

class paymentMethod {

     const NUMBER = 1;

}

echo paymentMethod::NUMBER;

How to use inheritance?

To inherit the properties and methods from another class, use the extends keyword in the class definition, followed by the name of the base class:

class Person {

}

class Employee extends Person {

}

What are interfaces and how to declare them?

Interfaces provide a way for defining contracts to which a class adheres; the interface provides method prototypes and constants, and any class which implements the interface must provide implementations for all methods in the interface. Here’s the syntax for an interface definition:

interface interfaceName {

   function functionName();

}

interface Printable {

   function printOutput();

}

class imageContent implements Printable {

   function printOutput() {

        echo “print this”;

   }

}

What is an abstract class?

PHP also provides a mechanism for declaring that certain methods on the class must be implemented by subclasses — the implementation of those methods is not defined in the parent class. In these cases, you provide an abstract method; in addition, if a class has any methods in it defined as abstract, you must also declare the class as an abstract class.

abstract class component {

   abstract function printOutput();

}

class imageComponent extends component {

   function printOutput() {

       echo “pretty picture”;

   }

}

Abstract classes cannot be instantiated. Also note that unlike some languages, you cannot provide a default implementation for abstract methods.

What is a constructor?

Quite simple. A constructor will run automatically after a class has been instantiated. So basically, you don’t need to call constructor. It executes it right after the instantiation is complete.

class Person {

    function __constructor($name, $age) {

         $this->name = $name;

         $this->age = $age;

    }

}

What are destructors?

When an object is destroyed, such as when the last reference to an object is removed or the end of the script is reached, its destructor is called. PHP automatically cleans up resources at the end of script’s execution.

class building {

     function __destruct() {

         echo “A building is being destroyed!”;

     }

}

What is introspection?

Introspection is the ability of a program to examine an object’s characteristics, such as its name, parent class(if any), properties, and methods. With introspection, you can write code that operates on any class or object. You don’t need to know which methods or properties are defined when you write your code; instead, you can discover  that information at runtime, which makes it possible for you to write generic debuggers, serializes, profilers, etc.

- Examining Classes

To determine whether a class exists or not, use the class_exists() function, which takes in a string and returns a Boolean value. Alternatively, you can use get_declared_classes() function, which returns an array of defined classes and checks if the class name is in the returned array:

$yes_no = class_exists(className);

$classes = get_declared_classes();

You can get the methods and properties that exist in a class (including those that are inherited from superclasses) using the get_class_methods() and get_class_vars() functions. These functions take a class name and return an array:

$methods = get_class_methods(className);

$properties = get_class_vars(className);

- Examining an Object

To get the class to which an object belongs, first make sure it is an object using the is_object() function, and then get the class with the get_class() function:

$yes_no = is_object(var);

$className = get_class(object);

Before calling a method on an object, you can assure that it exists using method_exists() function:

$yes_no = method_exists(object, method);

Just as get_class_vars() returns an array of properties for a class, get_object_vars() returns an array of properties set in an object:

$array = get_object_vars(object);

And just as get_class_vars() returns only those properties with default values, get_object_vars() returns only those properties that are set:

What is Serialization?

Serializing an object means converting it to a bytestream representation that can be stored in a file. This is useful for persistent data; for example, PHP sessions automatically save and restore objects. Serialization in PHP is mostly automatic — it requires little extra work from you, beyond calling the serialize() and unserialize() functions:

$encoded = serialize(something);

$something = unserialize(decoded);

Serialization is most commonly used with PHP’s sessions, which handle the serialization for you. All you need to do is tell PHP which variables to keep track of, and they are automatically preserved between visits to pages on your site. However, sessions are not the only use of serialization — if you want to implement your own from of persistent objects, the serialize() and unserialize() functions are a natural choice.