I'm trying to covert old code that uses functions to use classes. Some of the old code has options only available if an advanced option is set. In the base class I have put all of the functions (methods). If the function is available as an advanced option it is overriden in the second class. If not, it should say not available in the base class. The problem is that I can't figure out how to call one class or the other, short of putting in a bunch of if's, of course.
The original function would look like this
function Testclass() {
if (advanced_enabled)
return 'Do advacned stuff<br>';
else
return 'Do base stuff<br>';
}
Here are my classes:
class A {
public function Testclass() {
return 'in base class<br>';
}
public function SomeBaseCode() {
}
}
class B {
public function Testclass() {
return 'in advanced class<br>';
}
}
If I do this:
$a = new A();
echo 'base '.$a->Testclass();
$b = new B();
echo 'base '.$b->Testclass();
The output is
in base class
in advanced class
What I'm wanting to do is have the advanced class used if present. But the base class has to be present because it has methods always available. I can do this
$a = new A();
echo 'base '.$a->Testclass();
if (advanced_enabled) {
$b = new B();
echo 'base '.$b->Testclass();
}
But that gives me two different class variables and I would have to edit a lot of code to check each. I'm fairly new to classes so maybe I am missing some basic idea. Is there a way to do this?
Your advanced class B needs to extend from the base class A.
class A {
public function Testclass() {
return 'in base class<br>';
}
public function SomeBaseCode() {
}
}
class B extends A {
public function Testclass() {
return 'in advanced class<br>';
}
}
Instantiation is based on the advanced_enabled flag.
$a = advanced_enabled ? new A() : new B();
$a->SomeBaseCode();
$a->Testclass();