How can we efficiently handle adding and deleting child objects in a parent object in PHP?

When adding or deleting child objects in a parent object in PHP, we can efficiently handle this by using methods within the parent object to manage the child objects. This can involve methods like addChild() to add a child object and removeChild() to delete a child object. By encapsulating the logic for adding and deleting child objects within the parent object, we can ensure consistency and maintainability in our code.

class ParentObject {
    private $children = [];

    public function addChild($child) {
        $this->children[] = $child;
    }

    public function removeChild($child) {
        $key = array_search($child, $this->children);
        if ($key !== false) {
            unset($this->children[$key]);
        }
    }
}

// Example usage
$parent = new ParentObject();
$child1 = new ChildObject();
$child2 = new ChildObject();

$parent->addChild($child1);
$parent->addChild($child2);

$parent->removeChild($child1);