Classes & Objects

A class holds the methods and properties shared by all of the objects created from it. Although all the objects share the same code, they can behave differently because they can have different values assigned to them.

<?php

class Car {
    public $comp;
    public $color = 'beige';
    public $hasSunRoof = true;


}

$bmw = new Car();

$mercedes = new Car();

A class is defined in a block of code that starts with the class keyword followed by the name of the class. The variables inside a class is called the properties of the class. We can also write functions inside a class. The functions written inside a class are called methods of the class.

Creating Objects

We can create an object of a class using the following approach.

$bmw = new Car();

$mercedes = new Car();

Creating Methods

A class contain functions. The functions inside a class are knows as methods. Here we add the method hello to the class Car.

public function hello() 
{
    return "beep";
}

How to get the property of an object ?

Once we create an object we can get its properties. For example:

echo $bmw->color;
echo "<br />";
echo $mercedes->color;
echo "<br />";

How to set the property of an object ?

In order to set an object property we use the similar approach.

$bmw->color = "blue";
$bmw->comp = "BMW";
$mercedes->comp = "Mercedes Benz";

Here is the full source code for this chapter.

<?php

// Declare the class
class Car {
    // Properties
    public $comp;
    public $color = "silver";
    public $hasSunRoof = true;

    // Method to say Hello
    public function hello() 
    {
        return "beep";
    }
}

// Create the instance
$bmw = new Car();
$mercedes = new Car();

// Get the values
echo $bmw->color;
echo "<br />";
echo $mercedes->color;
echo "<br />";

// Set the values
$bmw->color = "blue";
$bmw->comp = "BMW";
$mercedes->comp = "Mercedes Benz";


// Get the values again
echo $bmw->color;
echo "<br />";
echo $mercedes->color;
echo "<br />";
echo $bmw->comp;
echo "<br />";
echo $mercedes->comp;
echo "<br />";

// use the methods
echo $bmw->hello();
echo "<br />";
echo $mercedes->hello();

Let us create a new class called User and practice what we have learned in Chapter 1.

<?php

class User {
    public $firstName;
    public $lastName;

    public function hello()
    {
        return "hello";
    }
}

$user1 = new User();
$user1->firstName = 'John';
$user1->lastName = 'Doe';

$hello = $user1->hello();

$user2 = new User();
$user2->firstName = 'Jane';
$user2->lastName = 'Doe';


echo $hello . ", " . $user1->firstName . " " . $user1->lastName;
echo "<br />";

echo $hello . ", " . $user2->firstName . " " . $user2->lastName;

results matching ""

    No results matching ""