我是PHP新手,遇到了一些奇怪的行为,这些行为在我的PHP版本(5.4.13)中可能是一个bug,也可能不是一个bug。我发现函数参数序列在函数声明中很重要。在以下示例中:
class Book {
function __construct() { }
public static function withDescriptors($isNotOrmObject, $isArray, $isScalar) {
$instance = new self();
// initialization here
return $instance;
}
}调用withDescriptors会导致‘数组字符串转换’异常。当调用withDescriptors时,即引发错误。withDescriptors从未被实际执行过。然而,使用数组参数切换对象参数可以解决这个问题。也就是说。
public static function withDescriptors($isArray, $isNotOrmObject, $isScalar){ ....这是PHP的一个已知特性,还是一个bug?
更明确地:
class Book {
function __construct() { }
public static function withDescriptors($isNotOrmObject, $isArray, $isScalar) {
$instance = new self();
// initialization here
return $instance;
}
}
$book = Book::withDescriptors($isNotORMobject, $isArray, $isScalar);失败了和
class Book {
function __construct() { }
public static function withDescriptors($isArray, $isNotORMobject, $isScalar) {
$instance = new self();
// initialization here
return $instance;
}
}
$book = Book::withDescriptors($isArray, $isNotORMobject, $isScalar);工作很棒。唯一的差异是参数序列,“这里的初始化”代码是相同的。
发布于 2013-05-25 15:33:46
这里有一些很好的答案,但是这种特殊情况是由PHP解释器中的一个bug引起的。
发布于 2013-04-07 11:47:19
在第二个示例中没有得到警告的原因是,作为第二个参数传递的Object正在实现一个神奇的__toString()方法。PHP不是一种强类型语言,但最近版本的类型提示能力有限。
说明警告;
function saySomething($shouldBeAString)
{
echo $shouldBeAString
}
saySomething(array('hello'));输出“阵列”
和一个警告array to string conversion
class Foo {
public function __toString() {
return 'Hi I am Foo';
}
}
$bar = new Foo();
saySomething($bar);威尔输出
'Hi I am Foo'毫无预兆
如前所述,PHP提供了有限的类型提示。您可以指定所需的“类/对象类型”和“数组”作为可接受的参数,但不能指定标量类型,如“string”、“int”、“bool”等。
function (array $myarray) {
// will only accept arrays
// or something that implements array-access
}
function (Foo $var) {
// Will only accept 'Foo' objects
}多态/功能超载
其他一些语言允许多次定义相同的方法/函数,但具有不同的签名(其他参数类型)。PHP并不明确支持这一点。
例如,在其他语言中,允许这样做:
function doSomething(string $arg1) { ......}
function doSomething(array $arg1) { .... }
function doSomething(string $arg1, string $arg2) { ... }在这些语言中,将根据参数的类型和数量执行变量1、2或3。PHP不支持这一点,因为它需要函数/方法具有唯一的名称。因此,PHP会抱怨已经定义了函数doSomething()。
但是,您可以在PHP中以多种方式创建类似的东西;
// rename the functions/methods so that they have a unique name
function _doSomething1(string $arg1) { ......}
function _doSomething2(array $arg1) { .... }
function _doSomething3(string $arg1, string $arg2) { ... }
// create the 'wrapper' function *without arguments specified*
function doSomething() {
// determin which variant should be executed
$numargs = func_num_args();
$args = func_get_args();
if ($numargs == 2) {
// 2 arguments -> variant 3
return call_user_func_array('_doSomething3', $args);
} else if {$numargs == 1) {
if (is_array($args[0]) {
// first argument is an array
return call_user_func_array('_doSomething2', $args);
} else {
return call_user_func_array('_doSomething1', $args);
}
}
}注:上面的代码是‘假’代码,只是为了说明这个想法!
发布于 2013-04-07 10:53:30
一般来说,顺序在函数参数中很重要。唯一的情况是,当参数是相同的类型时,或者函数实现了类似get opt long之类的东西时,就不会出现这种情况。
https://stackoverflow.com/questions/15861517
复制相似问题