Question

My problem in short is " I want to make a language system and I want to access to the phrases like this $language->fields->username->admin, so I tried to do that by different ways, but I can't merge a array to the object, I meaning I want to convert an array to an object and add this object that will return to the language object.

class Language
{
   public function __construct(array $array)
   {
       $this += (object) $array;
   }
}
Was it helpful?

Solution

You can't do that via a simple operator. You need to foreach over the array to assign the properties.

function makeObjectRecursively($array) {
    if (!is_array($array)) {
        return $array;
    }

    foreach ($array as $k => &$v) {
        $v = makeObjectRecursively($v);
    }
    return (object) $array;
}

foreach ($array as $k => $v) {
    $this->$k = makeObjectRecursively($v);
}

OTHER TIPS

What you describe sounds a bit like a RecursiveArrayObject:

class Language extends RecursiveArrayObject
{
    public function __construct(array $array)
    {
        parent::__construct($array, ArrayObject::ARRAY_AS_PROPS);
    }
}

$data = ['fields' => ['username' => ['admin' => 'ADMINv']]];

$language = new Language($data);

echo $language->fields->username->admin, "\n"; # prints "ADMINv"

That RecursiveArrayObject is a more concrete form of the ArrayObject:

class RecursiveArrayObject extends ArrayObject
{
    public function __construct(Array $array, $flags = 0, $iterator_class = "ArrayIterator")
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = new static($value, $flags, $iterator_class);
            }
            $this->offsetSet($key, $value);
        }
        $this->setFlags($flags);
        $this->setIteratorClass($iterator_class);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top