Reputation: 2527
I'm sure this will look like stupid question for most of you. However, I've been banging my head for quite a while over it. Coming from ASP.NET/C#, I'm trying to use PHP now. But the whole OOrintation gives me hard time.
I have the following code:
<html>
<head>
</head>
<body>
<?php
echo "hello<br/>";
class clsA
{
function a_func()
{
echo "a_func() executed <br/>";
}
}
abstract class clsB
{
protected $A;
function clsB()
{
$A = new clsA();
echo "clsB constructor ended<br/>";
}
}
class clsC extends clsB
{
function try_this()
{
echo "entered try_this() function <br/>";
$this->A->a_func();
}
}
$c = new clsC();
$c->try_this();
echo "end successfuly<br/>";
?>
</body>
</html>
To my simple understanding this code should result with the following lines:
hello
clsB constructor ended
entered try_this() function
a_func() executed
however, it does not run 'a_func', all I get is:
hello
clsB constructor ended
entered try_this() function
Can anyone spot the problem?
Thanks in advanced.
Upvotes: 1
Views: 97
Reputation: 3684
As the first answer but also you could extend the b class to the a class this way you can access the a class in C, like below:
<?php
echo "hello<br/>";
class clsA{
function a_func(){
echo "a_func() executed <br/>";
}
}
abstract class clsB extends clsA{
function clsB(){
echo "clsB constructor ended<br/>";
}
}
class clsC extends clsB{
function try_this(){
echo "entered try_this() function <br/>";
self::a_func();
}
}
$c = new clsC();
$c->try_this();
echo "end successfuly<br/>";
?>
Upvotes: 1
Reputation: 28929
Your problem lies here:
$A = new clsA();
Here, you're assigning a new clsA
object to the local variable $A
. What you meant to do was assign it to the property $A
:
$this->A = new clsA();
Upvotes: 9