Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php json_encode(…)是否可以使用数组返回false?_Php_Phpunit - Fatal编程技术网

Php json_encode(…)是否可以使用数组返回false?

Php json_encode(…)是否可以使用数组返回false?,php,phpunit,Php,Phpunit,我正在编写一些phpunit测试来检查我编写的自定义json类 我有一些代码我想测试 ... $contents = json_encode( $data ); if( false === $contents ) { ... } ... 但是如果“$data”是一个数组,它永远不会返回false,即使我传递了一些无效的参数,结果也会是类似于 {null:null} 当我传递数组时,如何测试encode_json(…)返回false?查看PHP文档中的json_last_error():

我正在编写一些phpunit测试来检查我编写的自定义json类

我有一些代码我想测试

...
$contents = json_encode( $data );
if( false === $contents )
{
  ...
}
...
但是如果“$data”是一个数组,它永远不会返回false,即使我传递了一些无效的参数,结果也会是类似于

{null:null} 

当我传递数组时,如何测试encode_json(…)返回false?

查看PHP文档中的
json_last_error()

它有一个导致
json_encode()
失败的示例,我在这里对其进行了调整,以使用数组进行演示:

<?php
// An invalid UTF8 sequence
$text = ["text" => "\xB1\x31"];

$json  = json_encode($text);
$error = json_last_error();

var_dump($json, $error === JSON_ERROR_UTF8);
?>

这是一个字符串,不是我问题中的数组,请尝试编码[“\xB1\x31”=>“\xB1\x31”],它不会返回false。不,正如我在问题中提到的,它是一个自定义类。但不管怎样,问题仍然存在,它如何能用数组返回false(比如字符串)。这个测试对我来说是通过的:公共函数testJsonEncodeReturnFalse(){$data=array(“\xB1\x31”=>”\xB1\x31”);$contents=json\u encode($data);$this->assertFalse($contents);}真的吗?,您使用的是什么版本的php?我使用完全相同的测试得到{null:null}。我在我的开发环境中使用了5.4.8(是的,我知道它接近eol,但仍然)。您好@FFMG我使用了我在5.4.x上测试过的5.5.x,并按照您的描述工作。我不知道为什么。希望对您有所帮助。您可以尝试使用使用runkit的phpunit扩展来模拟
json_encode
函数的行为
$ php php-test.php 
bool(false)
bool(true)