是否可以像在C++中一样在PHP中创建类模板?PHP可能没有类似的语言结构(如C++中的关键字),但也许有一些巧妙的技巧来实现类似的功能?template
我有一个Point
要转换为模板的类。在类中我使用类型参数,因此,对于每个类,我想传递给 Point 方法,我必须创建一个具有适当类型参数的 Point 类的新副本。
这是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;
}
在 PHP 中也是如此,但它根本不起作用(当然最后一行返回错误):
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;