I have 2 PHP class that related each other, rather than using __construct
, I tryin to using extends to combine these 2 class. But why sub class method cant called from parent class? There’s no either result or error displayed but warning about reach memory limit.
here my example code:
<?php
class Me
{
public $you;
public function __construct()
{
$this->you = new You;
}
public function Hi()
{
return 'Hi You';
}
public function WhatYouSaid()
{
return $this->you->Me();
}
}
class You extends Me
{
public function Me()
{
return 'Yes Me';
}
}
$talk = new You;
print_r($talk->WhatYouSaid());
I received error:
Fatal error: Allowed memory size of xxx bytes exhausted (tried to allocate xx bytes)
Based on @Nigel Ren answer i found solution here another example:
<?php
class DataValidate {
public $data;
public function __construct() {
$this->data = new Data;
}
public function inputValidate($newData)
{
// verifying
if ($this->data->get_data($newData['Identifier'], 'nameId'))
{
return false; // alredy exists
}
return $newData;
}
}
class Data {
public $db;
public $validate;
public function __construct() {
$this->db = new Database;
$this->validate = new DataValidate;
}
public function get_data($identifier, $col)
{
return $this->db->select($identifier, $col='*');
}
public function inputValidate($newData)
{
return $this->validate->inputValidate($newData);
}
}
$data = new Data;
print_r($data->inputValidate($some_id));
2
Answers
Each time you create a new object or type
You
, this calls the constructor inMe
. This then creates a new object of typeYou
, this calls the constructor inMe
…So you quickly run out of memory as it’s creating loads of new objects.
There is also a case of having a different method name, I have assumed that you meant to have the same name for the 2 output methods. You wouldn’t normally introduce a new method in a sub class.
So this code just calls the method on the current object rather than creating a new object to use…
Edit:
If you just want to make the idea of calling a method from another class, then using
extend
doesn’t help you at all. It just needs to be a class which has apublic
method to allow you to call.Then you create an instance of
Me
rather thanYou
and make the call…Actually the problem is that, each time you try to create a Me object, it instantiate a You object (as you set in Me‘s constructor).
As You extend Me, when you instantiate a You object, it starts by executing the code in Me‘s constructor, so you go into a non-stop loop. Then you run out of memory.