Is method signature in PHP a MUST or SHOULD?

这一生的挚爱 提交于 2019-12-24 05:39:07

问题


I mean if it's called with $request which is not instance of sfWebRequest ,will it be fatal,or just a warning?

class jobActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->jobeet_job_list = Doctrine::getTable('JobeetJob')
      ->createQuery('a')
      ->execute();
  }

  // ...
}

回答1:


It will be a catchable fatal error.

Here is an example:

class MyObj {}

function act(MyObj $o)
{
    echo "ok\n";
}

function handle_errors($errno, $str, $file, $line, $context)
{
    echo "Caught error " . $errno . "\n";
}

set_error_handler('handle_errors');

act(new stdClass());
/* Prints                                                                       
 *                                                                              
 * Caught error 4096                                                            
 * ok                                                                           
 */

If there wasn't a set_error_handler call the code will fail with an error:

Catchable fatal error: Argument 1 passed to act() must be an instance of MyObj, 
instance of stdClass given, called in /home/test/t.php on line 16 and defined in
/home/test/t.php on line 4



回答2:


See the chapter on TypeHinting in the PHP Manual

If $request is not a sfWebRequest instance or subclass thereof or implementing an interface of this name, the method will raise a catchable fatal error. Script execution will terminate if the error is not handled.

Example

class A {}
class B extends A {}
class C {}

function foo(A $obj) {}

foo(new A);
foo(new B);
foo(new C); // will raise an error and terminate script

With interfaces

interface A {}
class B implements A {}
class C {}

function foo(A $obj) {}

foo(new B);
foo(new C); // will raise an error and terminate script


来源:https://stackoverflow.com/questions/2161040/is-method-signature-in-php-a-must-or-should

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!