Reputation: 26762
I'm trying to find a way to 'redeclare' a class using a closure. This is what i've got so far:
I have two simple classes which are identical, except for the namespace. The namespace in test2.php is called "bla" and in new.php it's called "newname". Other than that, they are exactly the same.
namespace bla; //test2.php
class A
{
public function __construct()
{ }
public function bla()
{
echo '[A bla]';
}
}
include ("new.php");
include ("test2.php");
use newname\A as A; // <-- dynamic
$a = new A();
$a->bla();
So this piece of code simply executes the method from the 'new.php' class instead of the class in 'test2.php'. This is actually what i need. But my problem is the last part of the code. Normally i would've used a namespace:
$a = new bla\A(); //Defined in 'test2.php'
$a->bla();
But because of the 'use as' statement i have to change that line to:
$a = new A(); //Defined in 'test2.php'
$a->bla();
So without a namespace infront of "A()".
Is there a way to keep the "bla\A()" namespace (which is defined in test2.php), but that it still calls the method from "new.php" ??
Upvotes: 1
Views: 1527
Reputation: 3713
As it is said in comments, it is not a "closure" topic but only dynamic namespace topic.
I don't think you can use tue use
keyword dynamically.
However, PHP is a dynamic language, you can chose dynamically which class you want with meta-programming:
$wantedClass = 'myWantedNamespace\MyWantedClass';
$instance = new $wantedClass();
Upvotes: 1
Reputation: 5500
In this case , to call from each class , you should write =>
$bla = new bla/A("");
$bla->bla(); // to call from bla.php
and second class
$newname = new newname/A("");
$newname->something(); // to call from newname.php
and it will work , you do not need to overwork script with use keyword
also it is good practise to write classes in one file with namespaces like so =>
namespace bla{
class A{
// content
}
}
namespace newname{
class A{
// content
}
}
Upvotes: 1