PHP: Classes and Objects

Photo by Adrian N on Unsplash

PHP: Classes and Objects

·

2 min read

Classes

Creating Classes and Objects in PHP is similar to C++. Let's see an example of a Car class:

class Car
{
    public $name;            
    public $price;
    public function printInfo(){
        echo "This is a sports car";
    }   
}

Here, 'public' means the variable/method can be directly accessed. Now, to create an object from the class:

$car1 = new Car();           // Object Creation
// Output: This is a sports car
$car1->printInfo();
// Accessing and Defining object properties    
$car1->name = "Lamborgini";
$car1->price = "$200000";

Private Property

The private property can only be accessed and modified through the class's internal methods. Let's see an example of the same class containing a private variable in it.

class Car
{
    private $name;        
    // Class's internal methods    
    public function setName($value){
        $this->name = $value;            // Setting own 'name'
    }   
    public function getName(){
        echo "Car name is " . $this->name;
    } 
}

Here, '$this' refers to the particular object through which setName or getName is being called. Now, let's create an object and interact with a private variable.

$car2 = new Car();        
// $car2->name = "Lamborgini";        // Not Allowed
$car2->setName("Lamborgini");
// Output: Car name is Lamborgini
$car2->getName();

Constructor Function

It is a function that automatically runs when a new object is created. To initialize the object's property easily, we need to define a constructor function in the class as follows:

class Car{
    public $name;            
    public $price;
    // Constructor function 
    public function __construct($name, $price)
    {
        // Set variable of object as specified 
        $this->name = $name;
        $this->price = $price;
    }
}

Now, we can define an object's property when creating it as follows:

$car3 = new Car("Lamborgini", "$200000");
// Output: Lamborgini
echo $car3->name;
// Output: $200000
echo $car3->price;
💡
When defining a constructor function, we can define it with default parameters as well. Then we can simply create an object without passing any argument on it and get default values initialized in it.