我怎样才能减少这两行
$foo = new Bar();
$baz = $foo->methodOne('param')->methodTwo('param');
到
$baz = Bar::methodOne('param')->methodTwo('param');
我在 Laravel 中特别看到了它,它是很好的可读代码。但我坚持让它与一些自定义的帮助类一起工作。感觉就像是混合了静态 + 非静态函数,这目前令人困惑......
最佳答案
Laravel 通过以下方式实现
在:vendor/laravel/framework/src/Illuminate/Database/Capsule
/**
* Dynamically pass methods to the default connection.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
return call_user_func_array(array(static::connection(), $method), $parameters);
}
/**
* Get a connection instance from the global manager.
*
* @param string $connection
* @return \Illuminate\Database\Connection
*/
public static function connection($connection = null)
{
return static::$instance->getConnection($connection);
}
来自PHPDOC :
__callStatic() is triggered when invoking inaccessible methods in a static context.
我认为你可以为你的类(class)简化这个:
class Bar{
public static function __callStatic($method, $parameters)
{
return call_user_func_array(array(new Bar(), $method), $parameters);
}
public function hello(){
echo "hello";
}
}
Bar::hello();
关于php - 使用更少代码的流畅界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26441955/