开发者

Refactoring PHP OOP - How to get the object without passing a parameter?

I need t开发者_Go百科o refactor this code to not use a parameter when using the "save()" method.

The code is:

Person.php

class Person {

    public $name;
    public $age;
    public $country;

    public function save($object) {

        $api = new ReflectionClass($object);

        foreach($api->getProperties() as $propertie)
        {
            print $propertie->getName() . " - " . $propertie->getValue($object) . " | ";    
        }       
    }

}

?>

Example_usage.php

include_once('person.php');

$p = new Person();

$p->name = 'Mary';
$p->age = '28';
$p->country = 'Italy';
$p->save($p);

?>

My question. How can I use the "save()" method like this:

$p->save();

It is possible to pass the $p object in other way than passing the parameter in the "save()" method?


Current object is available with $this keyword you don't need to pass object just use $this inside the class method to point that object in your case $p

Modified method will look like this

public function save() {

        $api = new ReflectionClass($this);

        foreach($api->getProperties() as $propertie)
        {
            print $propertie->getName() . " - " . $propertie->getValue($this) . " | ";    
        }       
    }


You shouldn't use ReflectionClass for this purpose.

public function save() {
    echo $this->name; //etc
    // or maybe

    $name = mysql_real_escape_string($this->name);
    $age = ...
    $country = ... 

    mysql_query("INSERT INTO persons (name, age, country) values ('$name', '$age', '$country')");
}

If you would like to get each variable name together with its value, it's as easy this:

class test {
        public $key = 2;
        public $star = 'sun';
        private $planet = 'earth';

        public function save() {
                foreach($this as $key => $value) {
                         echo "$key => $value".PHP_EOL;
                }
        }

}

$t = new test();
$t->save();


Do you always want to pass the instance of the Person class from which you are calling the save method to the ReflectionClass?
Then you can also just pass $this which always references to the instance of the class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜