PHP的动态泛型

ExSystem 2010-04-24 10:58:54
一个PHP的动态泛型。我做的。下面是测试及使用的例子。。。

<?php
include 'FrameworkDSW/System.php';
class TChild extends TObject {
/**
* @param T $p
*/
public function Func($p) {
TType::Type($p, $this->GenericArg('T'));
}

/**
* @param T $t
* @param P $p
*/
public function FuncTwo($t, $p) {
TType::Type($t, $this->GenericArg('T'));
TType::Type($p, $this->GenericArg('P'));
}
}

TChild::PrepareGeneric(array ('T' => 'integer'));
$obj = new TChild();
$obj->Func(0);
$obj->Func(new TObject()); //此处出错!不是integer
$obj->Func(true); //不出错,因为true是可以转换成1的,根据PHP的==号规则
$obj->Func('string'); //不出错,因为可以转换成0,根据PHP的==号规则

TChild::PrepareGeneric(array ('T' => 'integer', 'P' => 'TObject'));
$obj = new TChild();
$obj->FuncTwo(0, new TObject());
$obj->FuncTwo(new TObject(), 0); //出错,TObject不是integer,0不是TObject

class TComplex extends TObject {
/**
* @param T $t
*/
public function Func($t) {
TType::Type($t, $this->GenericArg('T'));
}
}

TChild::PrepareGeneric(array ('T' => 'integer', 'P' => 'boolean'));
$c = new TChild();
TComplex::PrepareGeneric(array ('T' => array ('TChild' => array ('T' => 'integer', 'P' => 'boolean'))));
$obj = new TComplex();
$obj->Func($c);
$obj->Func(true);//出错:true不是TChild<T: integer, P: boolean>
...全文
1235 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
coder 2012-03-31
  • 打赏
  • 举报
回复
实际开发代码中,还没人尝试用吧?
gsk09 2012-03-27
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 exsystem 的回复:]

那么有没有必要把如何实现的代码贴出来呢??
[/Quote]

希望能分享代码
LKK 2010-12-06
  • 打赏
  • 举报
回复
收藏先。。
tata050 2010-12-06
  • 打赏
  • 举报
回复
好东西大家一起分享
happy664618843 2010-12-06
  • 打赏
  • 举报
回复
php比.NET要难些 看不懂
huangjian1110 2010-12-06
  • 打赏
  • 举报
回复
php里面有对象集合这么一说吗?就比如.net里面的LIst<T>泛型??
莱登堡 2010-04-26
  • 打赏
  • 举报
回复

TChild::PrepareGeneric()
initialize ...
$this->GenericArg()
object construct...
餅餅 2010-04-26
  • 打赏
  • 举报
回复
可以说php自身就是个泛型
床上等您 2010-04-26
  • 打赏
  • 举报
回复
嗯,不错的例子,学习了
sir424 2010-04-26
  • 打赏
  • 举报
回复
哈哈,收藏了
ExSystem 2010-04-26
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 lesorb 的回复:]
TChild::PrepareGeneric()
initialize ...
$this->GenericArg()
object construct...
[/Quote]
不是这样的。。。
是:

TChild::PrepareGeneric(array ('T' => integer));
$Obj = new TChild();
如果不需要泛型就是直接new,不要PrepareGeneric...


[Quote=引用 3 楼 bing19870624 的回复:]

可以说php自身就是个泛型
[/Quote]

我说的是类型安全 本身我的泛型也是动态的。。



那么有没有必要把如何实现的代码贴出来呢??

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧