<?php
class User
{
private static int $nextId = 1;
public readonly int $id;
public function __construct(public string $name)
{
$this->id = self::$nextId++;
}
public static function created(): int
{
return self::$nextId - 1;
}
}
$a = new User('Ada');
$b = new User('Grace');
$c = new User('Linus');
echo "{$a->name} #{$a->id}, {$b->name} #{$b->id}, {$c->name} #{$c->id}\n";
echo User::created(), " users created\n";
<?php
class Model
{
public static function createWithSelf(): Model
{
return new self();
}
public static function createWithStatic(): static
{
return new static();
}
public static function table(): string
{
return strtolower(static::class) . 's';
}
public static function tableWithSelf(): string
{
return strtolower(self::class) . 's';
}
}
class Post extends Model {}
class Comment extends Model {}
echo get_class(Post::createWithSelf()), "\n"; // Model
echo get_class(Post::createWithStatic()), "\n"; // Post
echo Post::table(), ', ', Comment::table(), "\n";
echo Post::tableWithSelf(), "\n";
<?php
class Counter
{
public static int $count = 0;
public static function increment(): void
{
static::$count++;
}
}
class Apples extends Counter {}
class Pears extends Counter
{
public static int $count = 0; // its own copy
}
Apples::increment();
Apples::increment();
Pears::increment();
echo 'Counter: ', Counter::$count, "\n";
echo 'Apples: ', Apples::$count, "\n";
echo 'Pears: ', Pears::$count, "\n";
<?php
// Static: one shared cart for the whole program
class StaticCart
{
private static array $items = [];
public static function add(string $item): void { self::$items[] = $item; }
public static function items(): array { return self::$items; }
}
// Object: each cart is separate
class Cart
{
private array $items = [];
public function add(string $item): void { $this->items[] = $item; }
public function items(): array { return $this->items; }
}
StaticCart::add('book');
StaticCart::add('pen'); // a "second customer" adds to the same cart
print_r(StaticCart::items());
$ada = new Cart();
$linus = new Cart();
$ada->add('book');
$linus->add('pen');
print_r($ada->items());
print_r($linus->items());