如果程序员不这样做,最好的解决方案是什么;t将参数传递给PHP OOP中的类方法


What is the best solution if programmer don't pass parameters to class method in PHP OOP?

我需要知道我们是否必须检查PHP OOP中类方法的输入参数
例如,想象下面的方法:

public function show_message($message)
{
   echo $message;
}

如果程序员不将消息参数传递给方法,那么最好的解决方案是什么?让PHP显示它的警告或运行时错误,或者做其他事情?

"最佳"解决方案取决于您希望该方法做什么,但通常,我建议将类型提示和默认值结合起来:

class Foo
{
    public function doSomething ($message = 'None')
    {
        echo $message;
    }
    public function somethingElse (array $foo = array())
    {
        echo '<pre>';
        print_r($foo);
        echo '</pre>';//will always be an array
    }
    public function onlyMyself (Foo $instance)
    {
        return $instance->doSomething('I know this method exists');
    }
    public function myselfOrNothing(Foo $instance = null)
    {
        if ($instance === null)
        {
            return $this->doSomething('No instance provided');
        }
        return $instance->doSomething('Instance provided to '.__METHOD__);
    }
}
$foo = new Foo;
$bar = new Bar;
$foo->onlyMyself($bar);//works fine
$foo->onlyMyself(array());//fails
$bar->myselfOrNothing();//works
$bar->somethingElse();//ok...

等等,你得到了基本原理
请注意,如果您使用的是一个抽象的父类(或任何旧的父类),则类型提示父类也允许传递子类:

class Bar extends Foo
{
}
class Foobar extends Bar
{
}
$fb = new Foobar;
$b = new Bar;
public function someClass(Foo $instance)
{//accepts instances of Foo, Bar and Foobar...
    echo get_class($instance);//can echo any class name
}

允许一个默认值,然后为该默认值设置陷阱。这将控制您的操作,而不是简单的默认PHP行为

public function show_message($message = "'x00")
{
    if ($message === "'x00") {
        // decide how critical this argument actually is, and react appropriately
        throw new BadMethodCallException("The message argument is critical and must be passed to this method");
        // or simply apply a default if it isn't critical
        $message = 'Hello World';
    }
    echo $message;
}

我认为错误的类型应该取决于函数的重要性,以及如果参数不存在,这是否足以作为停止执行的理由。

如果您谈论的是输入参数验证。你可以做这样的事。

public function show_message($message = '') {
  $result = 'No message';
  if (!empty($message)) {
    if (is_bool($message)) {
      $result = 'It is a boolean';
    }
    if (is_int($message)) {
      $result = 'It is a integer';
    }
    if (is_float($message)) {
      $result = 'It is a float';
    }
    if (is_string($message)) {
      $result = 'It is a string';
    }
    if (is_array($message)) {
      $result = 'It is an array';
    }
    if (is_object($message)) {
      $result = 'It is an object';
    }
  }
  return $result;
}