我有以下模型(对象),其中包含一些普通字段和嵌套数组。
我试图将模型转换为完整的数组,我遇到了一些技巧,例如以下内容。
public function getMessageArray()
{
return (array) $this->message;
}
但是,这给出了以下结果
另一个技巧是使用json_encode并解码如下:
$result= json_decode(json_encode($this->message), true);
但那是一个空数组。
App\Mailer\Models\Message {#505
-subject: "You bought products 3 days ago"
-fromEmail: "no-reply@test.be"
-fromName: "Webshop"
-replyTo: "no-reply@test.be"
-toEmail: "test@gmail.com"
-toName: "Myself"
-mergeVars: array:2 [
"rcpt" => "test@gmail.com"
"vars" => array:2 [
0 => array:2 [
"name" => "fname"
"content" => "My"
]
1 => array:2 [
"name" => "lname"
"content" => "Self"
]
]
]
}
这是print_r()
$this->message
我无法将$this->message
转换为数组以访问所有属性。知道我可能做错了吗?
答案 0 :(得分:1)
当属性为私有时,无法直接访问它们。 json_encode()
不对它们进行编码。
下面的PublicMaker
类提供对对象的所有属性的访问:私有和公共。
<?php
/*
* Make all the attributes of a class public
*/
class PublicMaker {
public $matches;
function __construct($obj) {
// explode object attribute and values
$print_r = print_r($obj, true);
preg_match_all('/\[(\w*).*\] => (.*)/', $print_r, $matches);
$this->matches = $matches;
}
function getArray() {
foreach($this->matches[1] as $key=>$match) {
$arr[$match] = $this->matches[2][$key];
}
return $arr;
}
// magic method to get any attribute of the object passed in the contructor
function __get($attribute) {
$match = array_search($attribute, $this->matches[1]);
if ($match !== FALSE) {
return $this->matches[2][$match];
} else {
return NULL;
}
}
}
// test values
class Message {
private $subject = 'You bought products 3 days ago';
private $fromEmail = "no-reply@test.be";
public $fromName = "Webshop";
}
// usage demonstration
$message = new Message();
$publicMessage = new PublicMaker($message);
$array = $publicMessage->getArray();
$subject = $publicMessage->subject;
echo '<pre> getArray: ';
print_r($array);
echo "\n Subject: $subject \n";
// other test values
echo "
Other test values:";
print_r((array) $message);
print_r($publicMessage->matches); // debug
echo "\n subject: ", $publicMessage->subject; // string(30) "You bought products 3 days ago"
echo "\n fromEmail: ", $publicMessage->fromEmail;
echo "\n fromName: ", $publicMessage->fromName;
echo "\n notExist ", $publicMessage->notExist;
var_dump($publicMessage->notExist); // NULL
可以在此处测试和优化正则表达式:http://www.phpliveregex.com/p/gje