Menu Close

Articles

PHP: Classes & Objects

You can say PHP is a multi-paradigm computer language. It is mostly imperative and structured but also object oriented. You can define classes, interfaces, traits and you can instantiate objects using a constructor, similar to other OOP languages.

OOP Properties

If you never new, or forget what OOP is all about, here is a short reminder. The three pillars of object oriented programming. PHP, is enabling all three of them  à la carte:

  • Encapsulation
  • Inheritance
  • Polymorphism

Classes 

A class is a code fragment identified by a name that can be used as a namespace or as a template. It is created with keyword “class” and it encapsulate declarations of variables called “properties” and functions that are called “methods”. There are some other keywords directly associated with declaration of a “class” but I will introduce you to an example and explain what is all about.

Example:

This example is a simplified class, to learn the basic principles:

Notes: 

  • You define a class with keyword: class,
  • Class name is case sensitive,
  • A class is a block of code,
  • A class can have nested functions, called methods,
  • You can create an “object” using keyword “new”,
  • You can access object methods using operator “->”
  • You can access object public properties using operator “->”

Possible beginner questions:

QuestionsAnswers
What is a Class?A Class is a template.
What is an Object?An object is an instance of a class.
Can I have more than one object?Yes you may have as many objects as you need.
Is a Class good for anything else?Yes, a Class can serve as a namespace.

Objects

An object is an instance of the class. The purpose of an object is to encapsulate data and methods that can deal with this data. That is first principle of the OOP: encapsulation.

There are two variables that are predefined in PHP and are very important: “self” and “$this”. Observe that “self” do not have $ prefix. 

  • self: represents the current class; 
  • $this: represents the current object instance

Notes:

  1. Members for “$this” are accessed using “member operator” that is “->”.
  2. Members for “self” are accessed using “scope operator” that is “::”.

Static members

Members of a class can be declared “static”. That means these members will belong to class and not to object. So if they belong to a class they can be used without instantiation, but there is a catch. In PHP accessing static members is done using symbol: “::” not “->”. 

Example:

Notes:

  • Static members can be used with class name using “::”,
  • Static members can be used with object name using “->”.

Inheritance

A class can be extended. That means we can create another class that can “extend” a base class. The new class has another name but “inherit” all the properties and all the methods of the “base class”. This is the second property of OOP.

Notes:

  • function printItem() is implemented two times and overwritten;
  • function printPHP() is implemented a single time and inherited;

Constructor

The constructor is a special function belonging to a class that is called automatically when an object is created using “new”. The constructor name is __construct() and is optional. If a class is extending another class, the parent constructor can be called explicit using scope: parent::__construct().

Example:

Note: Before PHP 5, constructor name was equal with class name. This convention is still available for backward compatibility. Many developers are using this convention so you may find old code without a _construct() method. Old style constructors are DEPRECATED in PHP 7.0.

Destructor

The destructor is a special method called __destruct() that has no parameters and no results. It is automatically called when an object goes out of scope. It can be used to release resources or to maintain static variables belonging to the class.

Example:

Note: A class can have multiple constructors with one or more parameters but only one destructor. 

Interface

A class can extend a single other class. So there is no multiple inheritance and this is problematic. To resolve this problem, object oriented programming is using concept of “Interface”. This is a special block of code that declare a “behavior” or “feature”. A class can “implement” one or more interfaces.

Example:

Output:

test: a = 10, b = 20

Note:

  • in previous example I have used keyword “private” to declare an internal attribute,
  • in interface, functions setVariable and getHtml are just declared not implemented,
  • in class, all functions that are declared by interface must be implemented.

Member visibility

The visibility of a property, a method or constant can be defined by prefixing the declaration with the keywords publicprotected or private

Notes:

  • Public members are visible from outside the class using object name and scope operators,
  • You can call private members only inside the class using self:: or $this->,
  • Protected members can be accessed from child classes but not from outside the class,
  •  Constants declared without any explicit visibility keyword are defined as public.

Abstract classes

These kind of classes are similar to interfaces, except they are designed to be inherited. They are usually base classes for some other classes that extend them. One abstract class can have many children, but each children can have only one parent class. 

Example:

Note: Abstract classes can declare abstract methods. These methods have only a signature. The implementation of the method is done in a concrete class. All the abstract methods must be implemented.

Traits

This is something very modern. It is an alternative form of code re-usability based on components. A trait is an “augment” that can be “used” into a class to extend its capabilities.

Unlike interfaces, traits have ready made functions, constants or variables. You do not have do implement them again in your class. When a trait is used, trait members become class members. 

Multiple traits can be combined into an “aggregate”, that is a larger trait.  By using the aggregate we can extend a class with functionality without writing new code and without using mix-ins.

Example:

Note: Using traits is a bit more complicated than this example but… that’s the essential. You can read more about traits in official manual when you are in position to use them.

Next article: Exception handling