PHP Class ‘Virtual’ Method using External File
I learn that when we include external file within a class method, the file will run in the class’ method context thus it can access the private members of the class (using $this keyword). The included file can also have return keyword inside it.
This capability could be useful in a case like we have several classes that need to share same method, but we don’t want to put it in a parent class (for reason that we might encountering need a multiple inheritance feature), neithermore, to have it written in each classes.
File: index.php
<?php
abstract class AbstractClass
{
public function sharedMethod()
{
$helper = new ClassHelper();
return $helper->helperMethod($this);
}
}
class ClassOne extends AbstractClass
{
private $arg = 'this is class ONE.';
public function classOneMethod()
{
return include('shared_method.php');
}
}
class ClassTwo extends AbstractClass
{
private $arg = 'this is class TWO.';
public function classTwoMethod()
{
return include('shared_method.php');
}
}
class ClassHelper
{
public function helperMethod($caller)
{
// error:
// $arg = $caller->arg;
$arg = 'ClassHelper Helper Method Called, but I can\'t call the Caller private property
';
return $arg;
}
}
// program
$classone = new ClassOne();
$classtwo = new ClassTwo();
echo '<p>'.$classone->sharedMethod().'</p>';
echo '<p>'.$classtwo->sharedMethod().'</p>';
echo '<p>'.$classone->classOneMethod().'</p>';
echo '<p>'.$classtwo->classTwoMethod().'</p>';
?>
File: shared_method.php
<?php $arg = $this->arg.' Shared Method Called! I am in the class context, so I can call private property'; return $arg; ?>
For this example, we must use include rather than include_once, to make sure that everytime any class include this file it will be executed.
Result in browser:
ClassHelper Helper Method Called, but I can't call the Caller private propertyClassHelper Helper Method Called, but I can't call the Caller private property
this is class ONE. Shared Method Called! I am in the class context, so I can call private property
this is class TWO. Shared Method Called! I am in the class context, so I can call private property
![]()
This method might need a scripting language like PHP and not a valid Object-Oriented approach. I can’t really tell you when the above case will happen because it just a matter of my personal opinion right now to have the classes’ methods written as separate file. I think it could be handy in the project files not to maintain business rule inside one big class file.
This method also related to my previous post about actor-centered business logic. This way, the Actor Service could handle same request without having to share another parent class (they should already have one).
