开发者

Strings before parameter definitions

开发者 https://www.devze.com 2023-02-07 08:37 出处:网络
It seems like PHP allows having strings (like the string foo in the example below) before parameters in function definitions.

It seems like PHP allows having strings (like the string foo in the example below) before parameters in function definitions.

function do_something(foo $param){开发者_如何学C}

Is this some kind of a feature?


This is some kind of type-safety feature in PHP

If you have

class Something {
 public function add(Something $s) { .. }
}

$s = new Something();
$s->add(new stdCLass());

This will throw catchable fatal error.

You can see it here - http://php.net/manual/en/language.oop5.typehinting.php


Yes, it's type hinting.


Yeah, In your example you are using type hinting, saying that parameter $param must be an instance of class "foo"


It is a way to define what type is allowed to be passed to the function. If you look at this comment on the PHP.net Function Arguments page you will see that you can define a class to be the type that is allowed.

0

精彩评论

暂无评论...
验证码 换一张
取 消