---
title: "Objects"
description: "Creating anonymous objects, defining methods, using $this, deleting properties, cloning, and reference semantics."
canonical_url: "https://www.zeyos.com/zymba/zymba-guide/objects-and-classes/objects"
markdown_url: "https://www.zeyos.com/ai/guide/zymba/zymba-guide/objects-and-classes/objects.md"
section: "zymba-guide"
authority: "draft-guide"
language: "en"
source_repository: "zeyos/guide"
source_path: "docs/zymba/05-objects-and-classes/objects.md"
source_revision: "cce886a8da98cd124ee3644711085bbdcf1a87ce"
---

# 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++;
    }
};
```
