Welcome Guest, Not a member yet? Register   Sign In
[solved] How do I create a new instance of self in a function and make it refer to the child when called from the child?
#1

[eluser]Jelmer[/eluser]
This might be a stupid question but I can't for the life of me figure out how to search this in Google or PHP.net and not get loads of (and as far as I can see: only) results I don't want.

I got a function that ends in:
Code:
$output = array();
$result = $this->db->get()->result_array();
foreach ($result as $row)
{
    $output[] = new self($row);
}
// Return array of objects
return $output;

This is from a CRUD/ORM like library I wrote that extends the basic CI model.

Each of my models extens the replacement model. When I ask it for multiple entries I want them to be returned as objects so I can use them as such. The problem is when I call this function from a child class it returns objects of the parent kind. How do I perform the "new self();" and make it refer to the class it's called from and not to the parent?

The function itself is a public function by the way, not static.

(I'll release this library once it works, but right now it's still too full of bugs to be released)
#2

[eluser]iFadey[/eluser]
What I understood from this is that the objects in array $output are of parent class? Are you talking about nested classes or inheritance?
By the way try "new ClassName()" instead of "new self()"
#3

[eluser]Jelmer[/eluser]
It's about inheritance.

The class itself is called MP_Model. When I call it from a childclass, for example "Pages", the objects it returns are of the kind MP_Model and not Pages.
Creating the objects with "new ClassName()" should give the same problem, but than I'd expect it. That would be "new MP_Model()", but I want that statement to mean "new Pages()" when called from Pages and something else when called from another childclass.
#4

[eluser]Jelmer[/eluser]
Solved it:
Code:
$class = get_class($this);
$output[] = new $class($row);
#5

[eluser]iFadey[/eluser]
Congrats Smile




Theme © iAndrew 2016 - Forum software by © MyBB