Reputation: 123
class A
{
public function child1()
{
$var1 = 'abc';
}
}
class B extends A
{
public function child1()
{
echo parent::$var1; // Return error undefined class constant 'var1'
}
}
How can i access $var1 in this situation ? Expected result: 'abc'
Upvotes: 1
Views: 49
Reputation: 3763
You need to make $var1 a class property. See following code:
<?php
class A
{
protected $var1;
public function child1()
{
$this->var1 = 'abc';
}
}
class B extends A
{
public function child1()
{
parent::child1();
echo $this->var1;
}
}
$b = new B();
$b->child1();
?>
Upvotes: 1
Reputation: 2971
First you cannot do class B extends class A
. The correct syntax would be class B extends A
:
class A
{
public function child1()
{
$var1 = 'abc';
return $var1;
}
}
class B extends A
{
public function child1()
{
echo parent::child1();
}
}
$temp = new B;
$temp->child1();
Now what I've done is return the $var1
in your class A
.
You cannot call echo parent::$var1;
because it is inside a function, so you call the parent function echo parent::child1();
.
Upvotes: 1