2017年2月22日 星期三

type juggling of PHP function default argument


在 php 版本 7.1.2 (Archlinux)
當 default argument 是 string ,
在指定 value 成 array 時會出現和預期不同的結果。

write2DBarcode([], 'QRCODE,H', 1,2,3,4);
Illegal string offset 'position'

tcpdf.php ( http://tcpdf.org/ )

public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='', $distort=false) {
        if (!isset($style['position'])) {
            $style['position'] = ''; // error line

        }
}

workaround:
write2DBarcode([], 'QRCODE,H', 1,2 ,3 ,4 , []);

雖然使用下列測試程式無法重現錯誤,可以得到和原本預期不同的輸出

function test($array1='') {
    $array1['id'] = 'myid';
    echo var_dump($array1);
}

test();


得到
string(1) "m"
而不是
string(1) "myid"

後來在 PHP:Type Juggling 有找到這個範例
<?php
$a    'car'// $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

可以解釋測試程式的輸出結果。

沒有留言:

張貼留言