What is the purpose of lazy loading in PHP and how can it be implemented?

Lazy loading in PHP is a technique used to defer the initialization of objects or resources until they are actually needed. This can help improve performance by only loading the necessary data when it is required, rather than loading everything upfront. Lazy loading can be implemented by using a proxy object that intercepts calls to the original object and loads it only when necessary.

class HeavyResource
{
    public function __construct()
    {
        // Simulate heavy resource initialization
        sleep(2);
    }

    public function doSomething()
    {
        echo "Doing something!\n";
    }
}

class LazyResourceProxy
{
    private $resource = null;

    public function doSomething()
    {
        if ($this->resource === null) {
            $this->resource = new HeavyResource();
        }
        $this->resource->doSomething();
    }
}

// Usage
$proxy = new LazyResourceProxy();
$proxy->doSomething();