๐ŸŽ“ A1Learner
๐Ÿ”

PHP Classes

A class is a plan that describes the data and actions of one kind of thing. Objects are the individual things built from that plan.

A Dog class and one object

The Dog class gives each dog a name property and a speak method. Both are public, so outside code can reach them. Inside speak, $this names the dog the call was made on.

<?php
class Dog {
  public $name = "";
  public function speak() {
    echo $this->name . " says Woof\n";
  }
}
$dog = new Dog();
$dog->name = "Rex";
$dog->speak();

Two objects, two names

Each object stores its own name value. The two speak lines show the separate values.

<?php
class Dog {
  public $name = "";
  public function speak() {
    echo $this->name . " says Woof\n";
  }
}
$first = new Dog();
$first->name = "Rex";
$second = new Dog();
$second->name = "Bella";
$first->speak();
$second->speak();

A method changes a property

The rename method writes a new name into the object. The speak line after it shows the change.

<?php
class Dog {
  public $name = "";
  public function speak() {
    echo $this->name . " says Woof\n";
  }
  public function rename($newName) {
    $this->name = $newName;
  }
}
$dog = new Dog();
$dog->name = "Rex";
$dog->rename("Max");
$dog->speak();

Example

<?php
class Dog {
  public $name = "";
  public $age = 0;
  public function speak() {
    echo $this->name . " says Woof\n";
  }
  public function profile() {
    echo $this->name . " is " . $this->age . "\n";
  }
}
$first = new Dog();
$first->name = "Rex";
$first->age = 3;
$first->speak();
$first->profile();
$second = new Dog();
$second->name = "Bella";
$second->age = 5;
$second->speak();
$second->profile();

Key points

  • Use the word class to write the plan.
  • Use new to make an object from a class.
  • A property is a value stored in an object.
  • A method is an action written inside a class.
  • public means code outside the class can reach the member.
  • Use $this-> to reach a member of the current object.
  • Each object holds its own property values.

In this example, the Dog class holds a name and an age for each object. The first dog speaks and prints its profile line. The second dog then speaks with its own name and age.

Note

A class name starts with a capital letter by custom.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

Which word makes a new object from a class?