I just learn deeper about OOP in PHP, but not an expert yet. I'm still a beginner. I have a problem. I want to pass the public value from parent class to child class. But I cant get it. I tried to find the answer in google and stackoverflow, and I have tried to follow the instruction, but it didnt work.
My code is like below:
class A
{
public $arrayperk;
public $nilai;
function __construct()
{
$this->nilai='This is bad';
}
function testParent()
{
return $this->arrayperk;
}
function testA()
{
return number_format(1000);
}
}
class B extends A
{
function coba()
{
return $this->testParent();
}
function coba2()
{
return $this->testA();
}
function coba3()
{
return $this->nilai;
}
}
The problem is that I want to pass the value of $arrayperk to the function inside class B. But it did not work at all.
My code is like below:
$arrayperk=Array( 1 => 'array1', 2 => 'array2');
$class_a=new A();
$class_a->arrayperk=$arrayperk;
$class_b=new B();
print_r($class_a->testParent()); //return array as needed.
print_r($class_b->coba()); //return nothing although it calls the parent class, and the parent work correctly if it is called like above. This is what I want to get and the problem I face.
echo $class_b->coba2(); //return 1,000 and it access the parent function
echo $class_b->coba3(); //return This is bad as written at parent class.
As you can see, the problem is at
$class_b->coba()
It gives nothing even I have call it correctly to the parent class, but the other test works fine when accessing the parent class function.
I am even unable to pass $this->arrayperk inside class B. It returns nothing. What am I missing? I cant get both $this->arrayperk and a function inside parent class.
Please help. Thanks.