Properties in OOP PHP

Those objects will all share the same characteristics defined by the class, but once they are instantiated, they will have a life of their own.

For example, a Dog has a name, an age, and a fur color.

So we can define those as properties in the class:

class Dog {
  public $name;
  public $age;
  public $color;
}

They work like variables, but they are attached to the object, once instantiated from the class. The public keyword is the access modifier and sets the property to be publicly accessible.

You can assign values to those properties in this way:

class Dog {
  public $name;
  public $age;
  public $color;
}

$roger = new Dog();

$roger->name = 'Roger';
$roger->age = 10;
$roger->color = 'gray';

var_dump($roger);

/*
object(Dog)#1 (3) {
  ["name"]=> string(5) "Roger"
	["age"]=> int(10)
	["color"]=> string(4) "gray"
}
*/

Notice that the property is defined as public.

That is called access modifier. You could use 2 other kinds of access modifiers: private and protected. Private makes the property inaccessible from outside the object. Only methods defined inside the object can access it.

We’ll see more about protected when we’ll talk about inheritance.

Download my free PHP Handbook!