($ foo)和(foo $ foo)之间的差异作为参数

could someone explain this to me?

What is the difference of these two methods?

function some_function($foo)
    {
    }

and

function some_function(foo $foo)
    {
    }

in my case

public function validate_something(notice $notice, $tok_id, $captcha) 
{
    if(something === true) {
        $notice->add('info', 'Info message');
    } else {
        $notice->add('error', 'Error message');
    }
}

$notice is a object of class notice

class notice {

    private $_notice = array();

    public function get_notice(){
        return $this->_notice;
    }

    public function add($type, $message) {
        $this->_notice[$type][] = $message;
    }
    ...
}

It's called type hinting

function some_function($foo)
{
}

Expects an argument to be passed to some_function when it is called

function some_function(bar $foo)
{
}

Expects an argument of datatype (class, abstract or interface, or array) bar to be passed to some_function when it is called.... if you pass an argument that isn't of this datatype, you'll get catchable fatal error

EDIT

What is the value of type hinting?

  • Because your code doesn't then need to use is_a or instance_of to validate arguments.
  • Reduces coding for defensive coders.
  • Functions/Methods are self-documenting for the arguments.

With this method:

function some_function($foo) {
}

You're expecting one parameter called internally in your function $foo

With this:

function some_function(foo $foo) {
}

You're expecting one parameter called $foo but it must be of type foo (an object of class foo)