我正在尝试从POST数据生成类Bar的对象。我正在使用我找到here的函数来执行此操作。
我将数据从foo.php发布到bar.php。 bar.php成功接收post数据并运行静态方法Bar :: generate,它返回一个Bar对象。
问题是,即使函数接收到正确的数据并知道在何处设置它,返回的对象属性也是空的。
foo.php
<?php
function postArray($array, $destScript){
try {
$ch = curl_init();
if (FALSE === $ch){
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_URL,$destScript);
curl_setopt($ch, CURLOPT_POST, count($array));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$content = curl_exec($ch);
return $content;
if (FALSE === $content)
throw new Exception(curl_error($ch), curl_errno($ch));
} catch(Exception $e) {
trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()),E_USER_ERROR);
}
}
echo postArray(array('action' => 'generate', 'first' => 'yes', 'second' => 'no', 'third' => 'maybe'), 'http://herbie.eu/indev/bar.php');
?>
bar.php
<?php
class Bar{
public $first;
public $second;
public $third;
private function __construct($options){
$this->loadFromArray($options);
}
private function loadFromArray($array) {
$class = new ReflectionClass(get_class($this));
$props = $class->getProperties();
foreach($props as $p) {
if (isset($array[$p->getName()])){
$p->setValue($this, $array[$p->getName]);
echo $p->getName()." = ".$array[$p->getName()]."<br>";
}
}
echo "<br>";
}
static public function generate($options){
try{
return new Bar($options);
}
catch(NotFoundException $unfe){
echo 'Bar::generate failed + '.$unfe;
return NULL;
}
}
}
if(!empty($_POST['action'])){
if($_POST['action'] == "generate"){
$booking = Bar::generate($_POST);
echo "success ".count($_POST)."<br>";
print_r($booking);
}
}
else{
echo "WARNING_L0: ${_POST}['action'] not set";
}
?>
运行foo.php返回,
first = yes
second = no
third = maybe
success 4
Bar Object ( [first] => [second] => [third] => )
正如您所看到的,loadFromArray中的ReflectionClass确切地知道要放在哪里,但返回的对象是空的。 4是计数的结果($ _ POST)。