繁体   English   中英

动态使用数组列表创建PHP对象

[英]Create a PHP Object using an Array List dynamically

我想在PHP中使用一个元素作为元素,使用从类外部函数获取的数组列表中获取的字段列表来创建对象。 我需要做这个,因为我必须从数据库编译数组,并且此数据列表可能会更改。 这可能吗? 我有一个函数叫做:

public $classKeyword = "contratti";
public $arrayList = getDbTableStructure($classKeyword);

这个函数返回数组列表,然后将其建立对象。 此函数在所有其他项目中均可使用(不使用类),但是如果我从类中调用它,则似乎无法使用...我正在丢失某些东西?

就像这样: (object) $array

您不能在调用它的地方调用该函数。 这是语法错误。

相反,您必须在构造函数中调用它。

<?php
    class MyClass {
        public $classKeyword;
        public $arrayList;
        public function __construct() {
            $this->classKeyword = "contratti";
            $this->arrayList = getDbTableStructure($this->classKeyword);
        }
    }
?>

为了创建动态对象,您可以考虑使用以下方法:

<?php

function getList() {
    return [
        'fieldName' => 'fieldValue',
        // other columns
    ];
}

$object = new stdClass();
foreach (getList() as $fieldName => $fieldValue) {
    $object->{$fieldName} = $fieldValue;
}

echo $object->fieldName . PHP_EOL;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM