lundi 8 février 2016

Object created using reflection and setValue has empty properties

I'm trying to generate an object of class Bar from POST data. I'm doing this using a function that I found here.

I post data from foo.php to bar.php. bar.php successfully receives the post data and runs the static method Bar::generate, which returns a Bar object.

The problem is, even though the function receives the correct data and knows where to set it, the returned objects properties are empty.

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://ift.tt/1nYhBZM');
?>

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";
    }
?>

Running foo.php returns,

first = yes
second = no
third = maybe

success 4
Bar Object ( [first] => [second] => [third] => )

As you can see, the ReflectionClass in loadFromArray knows exactly what to put where, but the returned object is empty. The 4 is the result of count($_POST).





Aucun commentaire:

Enregistrer un commentaire