A free and open-source book on ZF3 for beginners


3.1. PHP Classes

PHP supports object oriented style of programming (OOP). In OOP, the main building block of your code is a class. A class can have properties and methods. For example, let's create a PHP script named Person.php and define a simple class named Person in that file:

<?php 

class Person
{
    private $fullName;
    
    public function __construct()
    {
        // Some initialization code.
        $this->fullName = 'Unknown person';
    }
    
    public function getFullName()
    {
        return $this->fullName;
    }
    
    public function setFullName($fullName)
    {
        $this->fullName = $fullName;
    }
}

You may notice that in example above we have the opening <?php tag which tells the PHP engine that the text after the tag is a PHP code. In example above, when the file contains only the PHP code (without mixing PHP and HTML tags), you don't need to insert the closing ?> tag after the end of the code. Moreover, this is not recommended and may cause undesired effects, if you inadvertently add some character after the closing ?> tag.

The Person class above has a private property $fullName and three methods:

Once you have defined the class, you can create objects of that class with the new operator, as follows:

<?php 

// Instantiate the Person.
$person = new Person();

// Set full name.
$person->setFullName('John Doe');

// Print person's full name to screen.
echo "Person's full name is: " . $person->getFullName() . "\n";

Classes allow to split your functionality into smaller blocks and make it well organised. ZF3 consists of hundreds of classes. You will also write your own classes in your web applications.


Top