3

是否可以像在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;
4

1 回答 1

2

你能做的最好的就是 PHP 的eval类似特性,对象可以这样实例化:

$className = 'SomeClass';
$obj = new $className;

这一点,再加上梦幻般的动态类型应该足以允许:

$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;

必要的定义可能如下所示:

class Point
{
    public $x;
    public $y;

    public function __construct($className, $argX, $argY)
    {
        $this->x = new $className($argX);
        $this->y = new $className($argY);
    }
}

不过,我不确定我是否会推广这种代码风格。你原来的方法似乎更清晰、更干净。Point如果您愿意,可以在构造函数中执行两个参数共享相同类型的完整性检查。

于 2014-02-06T14:25:26.763 回答