获取通过PDO fetchAll(PDO :: FETCH_OBJ)从数据库检索的对象的属性

时间:2019-01-06 16:52:08

标签: php pdo

我确实使用PDO fetchALL(PDO :: FETCH_OBJ)从数据库中检索了对象数组。当我var_dump该数组的第一个元素时: var_dump($this->stockList[0]); 我得到:

object(stdClass)[5]
public 'userId' => string '3' (length=1)
public 'symbol' => string 'ibm' (length=3)
public 'date' => string '2019-01-03' (length=10)
public 'quantity' => string '5' (length=1)
public 'bought' => string '1' (length=1)
public 'observed' => string '0' (length=1)
public 'dividendRate' => string '6.28' (length=4)
public 'exDividendDate' => string '2018-11-08' (length=10)
public 'forwardDividend' => string '31.400000000000002' (length=18)

我想在此对象上使用反射来获取其所有属性:

$r = new ReflectionClass($this->stockList[0]);
$objProperties = $r->getProperties();

我上了正确的课: var_dump($r); 产生:object(ReflectionClass)[16] public 'name' => string 'stdClass' (length=8)

但是我无法获得该对象的属性: var_dump($objProperties); 给出一个空数组: array (size=0) empty 因此,问题是如何获取该对象的属性列表? 我的完整代码:

$sql = "query";
$this->stockList = $this->con->query($sql)->fetchAll(PDO::FETCH_OBJ);

var_dump($this->stockList[0]);
$r = new ReflectionClass($this->stockList[0]);
$objProperties = $r->getProperties();
var_dump($r);
var_dump($objProperties);

1 个答案:

答案 0 :(得分:2)

使用StdClass进行反射将不起作用。对参数vec <- structure(c(1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("männlich", "weiblich"), class = "factor") d <- data.frame(gender = vec) nums <- table(d) adj <- ifelse(nums > 15, 2, -2) ggplot(data = d, aes(x=gender,y=(..count..)/sum(..count..))) + geom_bar( fill="steelblue" ) + geom_text(aes(label = sprintf("%0.1f%%",(..count..)/sum(..count..)*100)), stat = "count", colour = "black", vjust = adj, fontface = "bold" ) 的调用使用实例的ReflectionClass()来确定其属性。由于StdClass默认情况下没有属性并且是动态提供的,因此Reflection找不到任何属性,因为默认情况下它们不存在。

您可以在demo中看到以上内容。但是,为了更加简单,这可以正常工作:

::class

但是,不要惊慌。您无需使用反射来执行此操作:var_dump(array_keys((array) new Foo('bar'))); # Based on above demo 将为您提供一个多维数组。您可以使用\PDO::FETCH_ASSOC来获取参数。然后,以后,如果您希望将结果用作对象,请将数组转换为对象。

array_keys()

替代地,如@Quasimodosclone的注释中所建议。您可以使用# Fetch Query $this->stockList = $this->con->query($sql)->fetchAll(PDO::FETCH_ASSOC); # Get properties which will be, in this case, ['id', 'symbol', 'date', 'quantity', 'bought', 'observed', 'dividendRate', 'exDividentDate', 'forwardDivident'] $properties = array_keys($this->stockList[0]); # Revert all back to StdClass instances by casting the array to object foreach($this->stockList as &$stockItem) { $stockItem = (object) $stockItem; } 来返回与对象等效的数组。然后,像以前一样,使用get_object_vars()来获取属性。

array_keys()

出于好奇而对此进行测试后,可以将该对象转换为数组以简化操作。

$this->stockList = $this->con->query($sql)->fetchAll(PDO::FETCH_OBJ);
$properties      = array_keys(get_object_vars($this->stockList[0]));