oobie11 oobie11 - 3 months ago 11
PHP Question

How do I get the calling instance of an object from inside a method in its parent class?

I have model class that looks like this

class Model {
public static function build(params=array()) {
$obj = WHAT DO I PUT HERE?

foreach($params as $key => $value) {
$obj->{$key} = $value;
}
...
}
}


My Modal class gets extended

class Post extends Model {
public $id;
public $title;
}


I want to be able to do this

$post = new Post;
$post->build(SOME_PARAMS);

print $post->title;


and have it print the title.

How would I go about this?

I have tried using
$this
in the Model class, but I get an error about using
$this
out of context.

Thanks.

Answer

Don't make the method static if it needs to access the object it's called through. In an ordinary method you can access the object with $this.

class Model {
  public function build(params=array()) {

    foreach($params as $key => $value) {
      $this->{$key} = $value;
    }
    ...
  }
}