PHP & OOP: Properties of a class

This entry is part 6 of 11 in the series PHP & OOP

Class member variables are called ‘properties‘.

When I first started learning OOP using C++, I thought this is odd.  It sounds abstract.

But look at the following declarations for the 2 class members and you might be able to understand.

<?php

class MovieStar
{
    public $person = 'Tom Cruise';
    public $salary = 10000;
    public $movie = 'Mission Impossible';
    public $no_of_movies = 20;
}

class PopStar
{
    public $person = 'Madonna';
    public $salary = 8000;
    public $album = 'Crazy For You';
    public $no_of_album = 12;
}

?>

From the class properties such as $movie and $album, we could guess what the 2 classes are about.

PHP & OOP: Instance of a class

This entry is part 4 of 11 in the series PHP & OOP

The keyword new is to create an instance of a class.

<?php
class SimpleClass
{
    public $var = 'a default value';

    public function displayVar() {
        echo $this->var;
    }
}

//create an instance of the class SimpleClass
$simple_object = new SimpleClass();
echo $simple_object->displayVar();

?>

As in the line

$simple_object = new SimpleClass();

You can also think of it as creating an object from the class SimpleClass.  With the instance $simple_object, we can access the class variable using

$simple_object->displayVar()

In PHP, we have used -> operator.  In other programming languages such as C++, we would have used the dot(.) operator.

PHP & OOP: A simple class declaration

This entry is part 3 of 11 in the series PHP & OOP

We first look at this simple class declaration.

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

$simple_object = new SimpleClass();
echo $simple_object->displayVar();

?>

In object-oriented terminology, a property is actually the variable of a class and a method is a function declared inside the class.

In the above example, we have used the method displayVar() to access the variable $var.  The variable $var is a property of the class SimpleClass.

Visibility

The visibility or scope of a property or method can be defined by prefixing the declaration with the keywords public, protected or private.

Class members declared public can be accessed everywhere.

Members declared protected can be accessed only within the class itself and by inherited and parent classes.

Members declared as private may only be accessed by the class that defines the member.