问题
Is is possible to create class template in PHP as in C++? PHP probably does not have a similar language structure (like template
key words in C++), but maybe there is some clever trick to achieve similar functionality?
I have a Point
class that I would like to convert to a template. In class I use typing arguments, therefore, for each class, I would like to pass to the Point method I have to create a new copy of Point class with appropriate types of arguments.
This is sample form C++:
#include<iostream>
template <typename T>
class Point
{
public:
T x, y;
Point(T argX, T argY)
{
x = argX;
y = argY;
}
};
int main() {
Point<int> objA(1, 2);
std::cout << objA.x << ":" << objA.y << std::endl;
Point<unsigned> objB(3, 4);
std::cout << objB.x << ":" << objB.y << std::endl;
return 0;
}
And the same in PHP, but it not work at all (of course the last but one line returns an error):
class SomeClass
{
public $value;
public function __construct($value = 0)
{
$this->value = $value;
}
}
class OtherClass
{
public $value;
public function __construct($value = 0)
{
$this->value = $value;
}
}
class Point
{
public $x;
public $y;
public function Point(SomeClass $argX, SomeClass $argY)
{
$this->x = $argX;
$this->y = $argY;
}
}
$objA = new Point(new SomeClass(1), new SomeClass(2));
echo $objA->x->value . ":" . $objA->y->value . PHP_EOL;
$objB = new Point(new OtherClass(3), new OtherClass(4));
echo $objB->x->value . ":" . $objB->y->value . PHP_EOL;
回答1:
The best you can do is PHP's eval
-like features, whereby objects can be instantiated like this:
$className = 'SomeClass';
$obj = new $className;
This, combined with the airy-fairy dynamic typing ought to be enough to allow:
$objA = new Point('SomeClass', 1, 2);
echo $objA->x->value . ":" . $objA->y->value . PHP_EOL;
$objB = new Point('OtherClass', 3, 4);
echo $objB->x->value . ":" . $objB->y->value . PHP_EOL;
The requisite definition may look like this:
class Point
{
public $x;
public $y;
public function __construct($className, $argX, $argY)
{
$this->x = new $className($argX);
$this->y = new $className($argY);
}
}
I'm not sure I'd promote this sort of code style, though. Your original approach seems clearer and cleaner. You can perform a sanity check inside the Point
constructor that both arguments share the same type, if you'd like.
来源:https://stackoverflow.com/questions/21605535/class-template-in-php-like-in-c