顺序匹配(Marching Order)
参数传递给函数的顺序是重要的。下面的例子要求名称作为第一个参数来传递,且位置作为第二个参数来传递。
<?php // define a function function introduce($name, $place) { print "Hello, I am $name from $place"; } // call function introduce("Moonface", "The Faraway Tree"); ?>
下面是输出结果:
Hello, I am Moonface from The Faraway Tree
在这个例子中,如果你颠倒了参数传递给函数的顺序,那么你将会看到:
Hello, I am The Faraway Tree from Moonface
然后看看,如果你完全忘记了传递一个需要的参数,会发生什么呢:
为了避免这样的错误,PHP允许你在用户定义的函数中为所有的参数指定缺省值。如果函数少调用了一些参数,那么这些缺省值就会被使用。下面是例子:Warning: Missing argument 2 for introduce() in xx.php on line 3
Hello, I am Moonface from
<?php // define a function function introduce($name="John Doe", $place="London") { print "Hello, I am $name from $place"; } // call function introduce("Moonface"); ?>
在这个例子中,输出将会是:
Hello, I am Moonface from London
请注意,即使函数定义中需要两个参数,但函数被调用的时候只有一个参数。然而,因为函数内每个参数都有缺省值,那个缺少的参数值被参数的缺省值来代替,因而没有错误产生。
Hello, I am The Faraway Tree from Moonface