<?php
class Model
{
protected $comments;
public function __construct()
{
$this->comments = new class {
public function count()
{
return rand(1, 20);
}
};
}
}
class Post extends Model
{
public function commentCount()
{
static $cache;
return $cache?: $cache = $this->comments->count();
}
}
$post = new Post();
var_dump($post->commentCount());
var_dump($post->commentCount());
var_dump($post->commentCount());
var_dump($post->commentCount());
var_dump($post->commentCount());