0

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

class MyClass{
    private $a = $r['a'];
    private $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.

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

ajreal has a good point, why are you creating a class with an array to hold the property values and magic getters/settings when mysqli_result::fetch_object (or mysql_fetch_object) can do the same thing without all the legwork?
1

Why reinvent the wheel ?

check this mysqli_result::fetch_object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.