php函数设定参数类型

php函数设定参数类型,第1张

php 函数的参数类型可以指定为类名或数组类型array,比如

这样是对的public function Right( My_Class $a, array $b )

这样是错的public function Wrong( string $a, boolean $b )

如果需要其他类型,需要在函数内部进行类型检查

参考

http://www.php.net/manual/zh/functions.arguments.php

这一段

public function Right( My_Class $a, array $b )

tells first argument have to by object of My_Class, second an array. My_Class means that you can pass also object of class that either extends My_Class or implements (if My_Class is abstract class) My_Class. If you need exactly My_Class you need to either make it final, or add some code to check what $a really.

Also note, that (unfortunately) "array" is the only built-in type you can use in signature. Any other types i.e.:

public function Wrong( string $a, boolean $b )

will cause an error, because PHP will complain that $a is not an *object* of class string (and $b is not an object of class boolean).

So if you need to know if $a is a string or $b bool, you need to write some code in your function body and i.e. throw exception if you detect type mismatch (or you can try to cast if it's doable).

function xinxi($name="",$sex="男",$age=1,$school="")

这样子的写法是正确的,

比如里边的, $school=""(表示,默认值为"")

调用的时候如下,

xinxi()//表示,参数为 $name="",$sex="男",$age=1,$school=""

xinxi(1)表示,参数为 $name="1",$sex="男",$age=1,$school=""

xinxi(1,1,1)表示,参数为 $name="1",$sex="1",$age=1,$school=""

相当于,缺少的参数,会使用对应的默认参数值

在www.php.net网站上下载一个windows版本的php压缩包,比如:php-5.6.23-win32-vc11-x86.zip,解压缩,然后找到php.ini-development,修改文件扩展名,得到php.ini,就可以进行参数配置了


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/6366891.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-21
下一篇 2023-03-21

发表评论

登录后才能评论

评论列表(0条)

保存