Object Oriented

Property

PHP

 

Defining Property

PHP 5
class Person {
  
  public $name;
  public $age;
  
}

Properties are like variables.

Properties keep the state of the current object.

public keyword defines the visibility of the property here. Check Visibility Topic for more on this.

 

Property initial value

PHP 5
class Person {
  
  public $name = "Sam";
  public $age = 25;
  
}

Properties in PHP can be initialized with values on declaration.

 

Accessing Properties

PHP 5
$person1 = new Person();

$person1->name = "Sarah";
$theName = $person1->name;   // "Sarah"

You can access properties (and methods) of an object using the -> operator (if that property is visible in that context. Check Visibility Topic for more on this).

Here, since $name is a public property (defined on previous cards) you can access it.

 

$this

PHP 5
class Person {
  
  public $name;
  public $age;
  
  public function greet() {
    print("Hi! I'm " . $this->name);
  }
  
  public function birthday() {
    $this->age = $this->age + 1;
  }
  
}

$this is a property in all classes pointing to the current object created from that class.

In order to access the properties and methods from within the class, you can use $this followed by -> operator.