tohokuaikiのチラシの裏

技術的ネタとか。

コンストラクタでPHPのクラスの確認をして、interfaceでなくてもnewできないクラスを作る

interface指定するとプロパティが使えなくなってしまうのが嫌なんですよ。

ということで、selfとget_classを使ってこんな感じ。

<?php
namespace Foo;
class ArgsP // このクラスはインスタンスを作らせたくない。
{
    function __construct(... $args){
        if (self::class === get_class($this)){
            throw new \Exception('クラスは作れません。');
        }
    }
}
class ArgsC extends ArgsP
{
    function __construct(... $args){
        parent::__construct(... $args);
    }
}
$a = new ArgsC(1, 2, 3); // O.K
$b = new ArgsP(1, 2, 3); // 例外発生