如何访问php类中动态定义的属性

如何访问php类中动态定义的属性

问题描述:

trying to develop a class associated with table(like in frameworks). assume we have a class named Book

class Book
{  
  public function save()
  {
     ....
  }

 }

$book = new book;
$book->id = '1';
$book->name = 'some';
$book->save();

the problem is how can i access this dynamically created properties inside save() to save new record

尝试开发一个与表相关的类(如在框架中)。 assume我们有一个名为Book的类 p>

  class Book 
 {
 public function save()
 {
 .... 
} 
 
} 
 
 $ book = new book  ; 
 $ book-> id ='1'; 
 $ book-> name ='some'; 
 $ book-> save(); 
  code>  pre> 
  
 

问题是如何在save()中访问这个动态创建的属性以保存新记录 p> div>

You could do it that way (note that there are other solutions to this problem) :

public function save() {
    $properties = get_object_vars($this);
    print_r($properties);
    // do something with it.
}

You can find properties in an object with:

$properties = get_object_vars($book);

See: http://php.net/manual/en/function.get-object-vars.php

here is complete code that you should use:

<?php 

class Book
{  
  public function save()
  {
     $vars = get_object_vars($this);
     var_dump($vars);
  }

 }

$book = new book;
$book->id = '1';
$book->name = 'some';
$book->save();

?>

</div>