是否可以用开关替换if( .. instanceof ...), elseif(... instanceof ...), ...块?例如:
if( .. instanceof ...), elseif(... instanceof ...), ...
<?php $class = ..... //some class if($class instanceof SomeClass) { //do something } elseif($class instanceof SomeAnotherClass) { //do something else }
0aydgbwb1#
对于instanceof的多态开关(考虑继承):
instanceof
switch(true) { case $objectToTest instanceof TreeRequest: echo "tree request"; break; case $objectToTest instanceof GroundRequest: echo "ground request"; break; }
对于类名应完全匹配的开关:
$class = get_class($objectToTest); switch($class) { case 'TreeRequest': echo "tree request"; break; case 'GroundRequest': echo "ground request"; break; }
qlckcl4x2#
以下是比较正确的:
$class = get_class($objectToTest); switch($class) { case TreeRequest::class: echo "tree request"; break; case GroundRequest::class: echo "ground request"; break; }
这样就可以正确地比较名称空间(您不必键入它们),如果名称空间或类名等任何内容发生更改,您将收到一个体面的IDE错误,通知您代码已损坏。
s3fp2yjn3#
使用match表达式,结果如下所示:
match
return match(get_class($object)) { TreeRequest::class => "tree request", GroundRequest::class => "ground request", default => "default request" }
记住它忽略了继承并且只接受当前类。考虑继承的匹配表达式:
return match(true) { $object instanceof TreeRequest=> "tree request", $object instanceof GroundRequest => "ground request", default => "default request" }
3条答案
按热度按时间0aydgbwb1#
对于
instanceof
的多态开关(考虑继承):对于类名应完全匹配的开关:
qlckcl4x2#
以下是比较正确的:
这样就可以正确地比较名称空间(您不必键入它们),如果名称空间或类名等任何内容发生更改,您将收到一个体面的IDE错误,通知您代码已损坏。
s3fp2yjn3#
使用
match
表达式,结果如下所示:记住它忽略了继承并且只接受当前类。考虑继承的匹配表达式: