Classes and Objects

Defining a Class and Creating Objects

A class declares properties and methods; new creates an object (new $name also works), -> reaches its members, and $this is the current object. PHP 8.4 lets you chain off new Product() without wrapping parentheses.

A first class, object handles and PHP 8.4 chaining off newPHP
<?php
class Product {
  public string $sku = '';
  public int $priceCents = 0;
  public function label(): string {
    return sprintf('%s $%.2f', $this->sku, $this->priceCents / 100);
  }
}
$a = new Product();                 // allocate an object from the class
$a->sku = 'BK-101';
$b = $a;                            // copies the handle, not the object
$b->priceCents = 1499;
echo $a->label(), ' |', new Product()->label(), "\n";   // PHP 8.4 chaining
debug_zval_dump($a);
Output
BK-101 $14.99 | $0.00
object(Product)#1 (2) refcount(3){
  ["sku"]=>
  string(6) "BK-101" interned
  ["priceCents"]=>
  int(1499)
}
Two variables, one object: the zval points at a refcounted zend_object
Two variables, one object: the zval points at a refcounted zend_object