<?php
class Apple
{
public function showColor()
{
return $this->color;
}
}
class Banana
{
public $color;
public function __construct()
{
$this->color = "Banana is yellow";
}
public function GetColor()
{
return Apple::showColor();
}
}
$banana = new Banana;
echo $banana->GetColor();
?>
I don't know how could the class Apple get $this->color from the Banana.
Banana class:
public function GetColor()
{
return Apple::showColor($this);
}
Apple class:
public static function showColor($banana)
{
return $banana->color;
}
Something is really wrong in your code.
Syntaxically, your code is not good.
It should be something like this:
<?php
class Apple
{
public function showColor()
{
return $this->color;
}
}
class Banana
{
public $color;
public function __construct()
{
$this->color = "Banana is yellow";
}
public function GetColor()
{
$apple = new Apple();
return $apple->showColor();
}
}
$banana = new Banana;
var_dump($banana->GetColor());
?>
With this good syntax, you are not able to get any values because no colors are defined in Apple class.
This is how the Apple
class gets the color
from the Banana
class: Actually, if you run the code having the E_STRICT
error reports turned on, a warning is generated saying:
Non-static method
Apple::showColor()
should not be called statically, assuming$this
from incompatible context in ...
This means that the PHP interpreter casts the $this
of the Banana
type to an incompatible Apple
object. The "incompatible type casting" is just like renaming the type-name of Banana
to the type-name of Apple
! The $this
(of type Banana
) has the field of color
, so does the new casted object of type Apple
.
Conceptually, this is what the interpreter does:
class Banana
{
.
.
.
public function GetColor()
{
$apple = cast($this, 'Apple'); // There is no such a cast() function in PHP,
// it is for demonstration purposes only!
// The $apple now has what $this already have!!
return $apple->showColor();
}
}