Objects
Anonymous objects
Create one-off objects with new object():
ZYMBA
$person = new object() {
name = "Alice";
age = 30;
};
echo $person.name; // "Alice"
echo $person.age; // 30
Objects with methods
Define methods directly in the object body. Use $this to reference the object itself:
ZYMBA
$counter = new object() {
value = 0;
increment() {
$this.value++;
}
decrement() {
$this.value--;
}
get() {
return $this.value;
}
};
$counter.increment();
$counter.increment();
$counter.increment();
echo $counter.get(); // 3
Reading and writing properties
Access properties with dot notation:
ZYMBA
$config = new object() {
host = "localhost";
port = 3306;
};
echo $config.host; // "localhost"
$config.host = "192.168.1.1"; // Modify property
Dynamic property access
Use bracket notation for dynamic property names:
ZYMBA
$field = "name";
$value = $person[$field]; // Same as $person.name
$person["age"] = 31; // Same as $person.age = 31
Deleting properties
Remove properties with delete:
ZYMBA
$data = new object() {
name = "test";
temp = true;
};
delete $data.temp;
// $data.temp is now undefined
Object cloning
Use clone to create an independent copy of an object:
ZYMBA
$Person = new object() {
name;
construct($n) { $this.name = $n; }
};
$original = new $Person("Alice");
$copy = clone $original;
$copy.name = "Bob";
echo $original.name; // "Alice" (unchanged)
echo $copy.name; // "Bob"
Reference semantics
Objects are passed by reference. Assigning an object to a new variable does not create a copy — both variables point to the same object:
ZYMBA
$a = new object() { x = 1; };
$b = $a; // $b is a reference to the same object
$b.x = 99;
echo $a.x; // 99 (both point to same object!)
$c = clone $a; // $c is an independent copy
$c.x = 42;
echo $a.x; // 99 (unchanged)
Common pitfall: forgetting $this
ZYMBA
// Wrong — creates a local variable, doesn't update the object
$Counter = new object() {
value = 0;
increment() {
$value++; // Local variable, not $this.value!
}
};
// Correct
$Counter = new object() {
value = 0;
increment() {
$this.value++;
}
};