Sage-Code Laboratory
index<--

PHP Classes

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 Concepts

PHP, enabling all three pillars of object oriented programmingà la carte. To learn PHP thorough you must understand these principles. We explain these concepts in our Computer Science course next year.

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. 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:

<?php
/* define a simple class */
class SimpleClass
{
    // property declaration
    public $var = 'default value';
    
    // method declaration
    public function displayVar() {
        echo $this->var,"<br>";
    }
}
// create a new object
$object = new SimpleClass;
// call a method
$object->displayVar();
// access public property
echo $object->var;
?>

Notes: 

Frequent Q&A:

Questions Answers
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.

PHP Objects

An object is an instance of a 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. Though self keyword is also used in Python and Java, for PHP this keyword has a very distinct significance:

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 :: notthe common symbol -> that may be familiar to you from C language (or not). 

Example:

<?php
/* define a abstract class */
class Foo
{
    public static $my_static = 'foo';
    public static function staticValue() {
        return self::$my_static;
    }
}
//accessing static property
echo Foo::$my_static; // foo
echo "<br>";
//accessing static method
echo Foo::staticValue(); // foo
echo "<br>";
?>

Notes:

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.

<?php
const EOL = "<br>";
// base class
class Foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . EOL;
    }
    public function printPHP()
    {
        echo 'PHP is great.' . EOL;
    }
}
// extended class
class Bar extends Foo
{
//overvrite function: printItem
    public function printItem($string)
    {
        echo 'Bar: ' . $string . EOL;
    }
}
$foo = new Foo(); // base object
$bar = new Bar(); // extended object
/* using extended object */
$foo->printItem('foo'); // Output: 'Foo: foo'
$foo->printPHP(); // Output: 'PHP is great'
/* using extended object */
$bar->printItem('bar'); // Output: 'Bar: bar'
$bar->printPHP(); // Output: 'PHP is great'
?>

Notes:

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:

<?php
class BaseClass {
    function __construct() {
        echo "BaseClass constructor","<br>";
    }
}
class SubClass extends BaseClass {
function __construct() {
        parent::__construct();
        echo "SubClass constructor","<br>";
    }
}
$obj = new BaseClass();
$obj = new SubClass();
?>

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:

<?php
class MyClass {
    function __construct() {
        print "In constructor\n";
    }
    function __destruct() {
        print "Destroying " . __CLASS__ . "\n";
    }
}
$obj = new MyClass();

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:

<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}
// Implement the interface
class Template implements iTemplate {
    private $vars = array();
    public function setVariable($name, $var) {
        $this->vars[$name] = $var;
    }
    public function getHtml($template) {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
        return $template;
    }
}
//use Template class
$temp = new Template;
$temp->setVariable("a",10);
$temp->setVariable("b",20);
echo $temp->getHTML("test: a = {a}, b = {b}");
?>

Output:

test: a = 10, b = 20 

Note:

Member visibility

The visibility of a property, a method or constant can be defined by prefixing the declaration with the keywords: { public, protected, private};

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:

<?php
abstract class AbstractClass
{
// Our abstract method only needs to define the required arguments
    abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
//  Our child class may define optional arguments not in the parent's signature
    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {
            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {
            $prefix = "Mrs";
        } else {
            $prefix = "";
        }
    return "{$prefix}{$separator} {$name}";
    }
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "<br>";
echo $class->prefixName("Pacwoman");
?>

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:

<?php
/* define first trait */
trait Hello {
        public function sayHello() {
        echo 'Hello ';
    }
}
/* define second trait */
trait World {
    public function sayWorld() {
        echo 'World';
    }
}
/* using two traits */
class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}
/* testing the new class */
$o = new MyHelloWorld();
$o->sayHello(); //first trait function
$o->sayWorld(); //second trait function
$o->sayExclamationMark(); //class function
?>

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 situation to start using them. Until you do, let's continue with something else that may be more important.


Read next: Exceptions