- var_dump: documentation ( source)
- rand: documentation ( source)
<?php
class Model
{
protected $comments;
public function __construct()
{
$this->comments = new class {
public function count()
{
$responses = [
1,
2,
3,
"Error: could not connect to database",
5
];
$rand = rand(0, 4);
if (is_string($responses[$rand])) {
throw new Exception($responses[$rand]);
}
return $responses[$rand];
}
};
}
}
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());