php中json解码和对象的区别
如果我发送消息php中json解码和对象的区别,php,json,oop,Php,Json,Oop,如果我发送消息 curl -i -H "Content-Type: application/json" -X POST \ -d '{"name": "Bob", "age": 32}' \ http://localhost:8000/user.php 在包含user.php的目录上运行php-S localhost:8000时: <?php class User { public $name, $age; function _
curl -i -H "Content-Type: application/json" -X POST \
-d '{"name": "Bob", "age": 32}' \
http://localhost:8000/user.php
在包含user.php
的目录上运行php-S localhost:8000
时:
<?php
class User {
public $name, $age;
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$user1 = json_decode(file_get_contents('php://input'), true);
$user2 = new User("Bob", 32);
?>
$user1和$user2之间有什么区别吗?如果是,如何将消息直接解码到类User的实例中?如果否,这是否意味着在上面的示例中类用户是完全冗余的
文件:
false
作为第二个参数,否则结果(当前获取的)是关联数组。注意false
是第二个参数的默认值,因此您可以在这里省略它
假设您没有为json_decode
的第二个参数传递true
,那么示例中的$user1
是的一个实例,而$user2
是User
的一个实例,因此实例属于不同的类
如果要将输入输入到用户
实例中,可以执行以下操作
$rawUser = json_decode(file_get_contents('php://input'));
$user1 = new User($rawUser->name, $rawUser->age);
另一种方法可能是静态
工厂方法
class User {
public $name, $age;
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
static public function fromRaw(stdClass $rawUser) {
$newUser = new self();
$newUser->name = $rawUser->name;
$newUser->age = $rawUser->age;
return $newUser;
}
}
然后您可以将第一个示例修改为
$rawUser = json_decode(file_get_contents('php://input'));
$user1 = User::fromRaw($rawUser);
而不是
newuser()代码>,你应该使用新自我()代码>。在这里试试:@quickshiftin听起来不错,几乎非常清晰!但还有一点:让json_decode
先构造stdClass
的实例,然后在构造我们真正想要的对象之前只保留一瞬间,这似乎是浪费。然而,除了自己解析file_get_contents返回的字符串之外,这就足够了。你能发表意见吗?@Calif问题是JSON不是php的本机格式。如果改为使用,则可以将类的实例作为字符串传递,然后在调用时,该实例将立即可用,而无需JSON方法的中间步骤。