0

如何在波纹管类中打印动态添加属性?

class Car {

    function __construct() {
    }

    function setInfo($car_arr) {
            foreach ($car_arr as $key => $value) {
                $this->{$key} = $value;
            }
    }

   }

像下面这样设置类对象

$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));

$car2 = new Car();
$car2->setInfo(array('anme1' => 'value1', 'anme2' => 'value2'));

现在我想在下面打印汽车对象

make = Toyota
model = scp10
4

5 回答 5

2

尝试 :

$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));

echo $car1->make;
echo $car1->model;
于 2013-03-21T11:45:20.863 回答
1

请考虑像我在此答案中指出的那样明确存储属性:

<?php
class Car {
  private $data = array();

  function setInfo(array $carInfo) {
    foreach ($carInfo as $k => $v) {
      $this->data[$k] = $v;
    }
    return $this;
  }

  function __set($key, $val) {
    $this->data[$key] = $val;
  }
  function __get($key) {
    return $this->data[$key];
  }
}

$car = new Car();
$car->setInfo(array('make' => 'Toyota', 'warranty' => '5 years'));

我认为它更“干净”,但这可能值得商榷。

于 2013-03-21T13:03:33.693 回答
1
<?php
    class Car {

        function __construct() {
        }

        function setInfo($car_arr) {
                foreach ($car_arr as $key => $value) {
                    $this->{$key} = $value;
                }
        }

       }
    $car1 = new Car();
    $car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));

    echo "Make value is : " . $car1->make. ", Model value is : ". $car1->model;
?>

以上代码输出Make value is : Toyota, Model value is : scp10

于 2013-03-21T11:46:46.240 回答
0

我认为您正在寻找类似PHP 魔术方法的东西

比如这个:

<?php

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

也会很有帮助。

于 2013-03-21T11:50:35.463 回答
0

您可以使用 get_object_vars() 获取所有属性:

$vars = get_object_vars($car1);
foreach ($vars as $key => $value) {
  echo $key . ' = ' . $value . '<br />';
}
于 2013-03-21T11:54:30.293 回答