开发者

PHP Class: mysql data as a property

开发者 https://www.devze.com 2023-02-04 15:19 出处:网络
I want to create properties that are set to mysql data. class MyClass{ private $a = $r[\'a\']; priv开发者_如何学JAVAate $b = $r[\'a\'];

I want to create properties that are set to mysql data.

class MyClass{
    private $a = $r['a'];
    priv开发者_如何学JAVAate $b = $r['a'];
    private $c = $r['c']; 
}

I know this is incorrect syntax but I want you to get the idea.

I could create a method that returns a requested mysql data, but I don't want the function to be called for every single row.


You need to implement the magic method __get.

Something like:

class MyClass {
  protected $_row = array();

  public function __get( $name )
  {
    if (array_key_exists($name, $this->_row)) {
      return $this->_row[$name];
    }
    return null;
  }

  public function __isset( $name )
  {
    return array_key_exists($name, $this->_row);
  }
}

And you could used as:

$obj = new MyClass();
$obj->load(); // Or any method to load internal data
echo $obj->a . $obj->b;


Why reinvent the wheel ?

check this mysqli_result::fetch_object

0

精彩评论

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