【发布时间】:2014-02-06 14:24:07
【问题描述】:
是否可以像在 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;
【问题讨论】:
-
public function Point()应该是public function __construct()
标签: php c++ class-template