我正在尝试使用Steam API数据,因为我喜欢在实例上学习,并查看返回各种统计信息的方式,我开始认为在这种情况下OOP方法最适合我。
我想要实现的是循环遍历所有结果,并以编程方式使用与统计信息的实际类型对应的类型的对象填充数组。我试图构建我自己是一个基本的类,称为统计,并且在实例化一个对象后确定它的类是否应该改变(即是否要转换一个类型的对象,Statistic是父类,如果是,则是什么类型)。如何在PHP中做到这一点?我的解决方案没有给我带来好运,所有对象都是Statistic类型,它的'type'属性是我想单独存储在数组中的对象。代码:
$data = file_get_contents($url);
$data = json_decode($data);
$data = $data->playerstats;
$data = $data->stats;
$array;
for($i=0;$i<165;$i++)
{
$array[$i] = new Statistic($data[$i]);
echo "<br/>";
}
var_dump($array[10]);
班级代码:
<?php
class Statistic
{
public function getProperties()
{
$array["name"] = $this->name;
$array["value"] = $this->value;
$array["type"] = $this->type;
$array["className"] = __CLASS__;
return json_encode($array);
}
public function setType($x)
{
$y = explode("_",$x->name);
if($y[0]=="total")
{
if(!isset($y[2]))
{
$this->type = "General";
}
else
{
if($y[1]=="wins")
{
$this->type = new Map($x);
$this->__deconstruct();
}
if($y[1]=="kills")
{
$this->type = new Weapon($x);
$this->__deconstruct();
}
else $this->type="Other";
}
}
else $this->type = "Other";
}
function __construct($obj)
{
$this->name = $obj->name;
$this->value = $obj->value;
$this->setType($obj);
}
function __deconstruct()
{
echo "deconstructing <br/>";
return $this->type;
}
}
class Weapon extends Statistic
{
public function setType($x)
{
$y = explode("_",$x);
if($y[1]=="kills")
{
$this->type = "kills";
}
else if($y[1]=="shots")
{
$this->type = "shots";
}
else if($y[1]=="hits")
{
$this->type = "hits";
}
}
function __construct($x)
{
$name = explode("_",$x->name);
$this->name = $name[2];
$this->value = $x->value;
$this->setType($x->name);
}
function __deconstruct()
{
}
}
class Map extends Statistic
{
public function setType($x)
{
if($x[1]=="wins")
{
$this->type = "wins";
}
if($x[1]=="rounds")
{
$this->type = "rounds";
}
}
public function setName($name)
{
if(isset($name[3]))
{
if(isset($name[4]))
{
return $name[3] + " " + $name[4];
}
else return $name[3];
}
else return $name[2];
}
function __construct($x)
{
$name = explode("_",$x->name);
$this->name = $this->setName($name);
$this->value = $x->value;
$this->setType($name);
}
function __deconstruct()
{
}
}
给出结果:
object(Statistic)#223 (3) {
["name"]=> string(18) "total_kills_deagle"
["value"]=> int(33)
["type"]=> object(Weapon)#222 (3) {
["name"]=> string(6) "deagle"
["value"]=> int(33)
["type"]=> string(5) "kills" }
}
如果这个决定是从循环本身驱动的,那么拥有一组为我做所有事情并返回准备服务数据的函数的全部优势都消失了,因为我真的要投出不同的对象。没有相互联系,这不是这里的情况。 如何实现与对象本身不同类型的返回对象?
答案 0 :(得分:0)
回答你的问题如何实现与对象本身不同类型的返回对象?
“在PHP中无法使用转换来更改对象的类型(不使用令人讨厌的扩展名)”
了解更多信息:Cast the current object ($this) to a descendent class
因此,您无法使用派生类的类型更改实例的类类型。在其他世界中,无法使用Static
的实例更改Weapon
的实例。