0

I want to create an Object in PHP using, as element, a list of fields taken from an array list obtained from a function outside the class. I need to do that dinamically, cause I have to compile the array from a DB and this list of data could change. Is this possible? I've a function called:

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

And this function return me the array list and I'll cicle it to build the object. This function work in all other the project (not using class), but seems not working if I call it from a class... I'm losing something?

1
  • Don't know if you lost something, but you might want to give us a little more code so we have a better understanding of the problem you are having. Sorry for posting it as an answer, hit the wrong button, didn't really think about it. Commented Oct 24, 2014 at 13:40

3 Answers 3

1

just do like this: (object) $array

Sign up to request clarification or add additional context in comments.

1 Comment

Right, I haven't thought about that.
0

You cannot call the function where you are calling it. It is a syntax error.

Instead you must call it in the constructor.

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

Comments

0

For creating dynamic objects you might consider using something like this:

<?php

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

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

echo $object->fieldName . PHP_EOL;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.