猿问

如果包含空值,php 是否有办法停止调用链?

我想做,但可以回来。self::container()->get($path);self::container()null


有没有一种更快的方法来避免在链接函数调用时出错,并且有些方法可以返回null而不是对象?Call to a member function get() on null


有没有比嘲笑预期对象/成员的丑陋解决方法更好的方法?


public static function getDependency($path) {

 return self::container() ??

  (new class{public function get($path){return null;}})->get($path);

}

我所追求的是类似于C中的空条件成员访问运算符()#?.


幕布斯6054654
浏览 115回答 2
2回答

浮云间

随着即将到来的 PHP 8,nullsafe_operator将被实现,如果其中一个调用返回 null,则允许对一系列调用进行断路   $result = $o->returnNull()?->doSomething()   $results === null // True

30秒到达战场

此答案适用于早于 8.0.0 的 PHP 版本。对于 PHP 8.0.0 及更高版本,请参阅 Maks3w 答案简短的回答:不,PHP中没有这样的东西。我会避免,不惜一切代价,做魔术,就像你建议的那样。行为:<?phppublic static function getDependency($path) {&nbsp; &nbsp; $container = self::container();&nbsp; &nbsp; if ($container instanceof ContainerInterface) {&nbsp; &nbsp; &nbsp; &nbsp; return $container->get($path);&nbsp; &nbsp; }}会更容易阅读/理解。现在,关于,它已被自己的创造者(托尼·霍尔)描述为“十亿美元的错误”。null更好的方法是作为返回类型,而不可能是。试图返回一个,它会抛出一个,可能会被抓住。这样,对 的调用将永远不会发生,因为异常将之前被抛出。self::container()ContainerInterfacenullnullTypeError->get()允许返回类似的东西将导致所有调用方实现您建议的逻辑,这也会导致(大量)重复的代码。self::container()ContainerInterface|null出于同样的原因,为依赖项指定特定的返回类型可能会更安全:<?phppublic static function getServiceFoo($path): ServicFoo {&nbsp; &nbsp; $container = self::container();&nbsp; &nbsp; if (!$container instanceof ContainerInterface) {&nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException("Not a valid container received");&nbsp; &nbsp; }&nbsp; &nbsp; return $container->get($path);}否则,您将面临与 上已经存在的相同的问题。getServiceFoo()self::container()
随时随地看视频慕课网APP
我要回答