I have a parent class Base
abstract class Base
{
protected $prop1 = null;
protected $prop2 = null;
}
And in the child class I want to change the both of property
class Child extends Base
{
public function method1($val1, $val2)
{
$this->prop1 = $val1;
$this->prop2 = $val2;
}
public function method2()
{
echo prop1;
echo prop2;
}
}
Is there any way to get changed values after calling first method of child class and after when I calling the second method of the child class? I tried to do that but I'm getting not changed values in this exsample thay are null's.
Use $this->prop1
to read the prop1
property:
class Child extends Base{
public function method1 ($val1, $val2) {
$this->prop1 = $val1;
$this->prop2 = $val2;
}
public function method2 () {
echo $this->prop1;
echo $this->prop2;
}
}
Read about OOP in PHP in the docs.
You have to handle prop1 and prop2 as class properties. Therefore - object scope/context - you have to write in code (whenever you read/write their values) as you have done it in method1():
public function method2() {
echo $this->prop1;
}
In child class method2 you are not referring to actual properties. use $
otherwise php
will understand it as a constant
<?php
abstract class Base
{
protected $prop1 = null;
protected $prop2 = null;
}
class Child extends Base
{
public function method1($val1, $val2)
{
$this->prop1 = $val1;
$this->prop2 = $val2;
}
public function method2()
{
echo $this->prop1;
echo $this->prop2;
}
}
$child = new Child();
$child->method1(30, "ABC");
$child->method2(); //will show 30ABC
?>