Skip to content

$object->get('foo'); is hard to unbox #9

Description

@lachlankrautz

I have an array object with a nested value "foo" that is sometimes an array sometimes a string.

I need to access "foo" and get the underlying object not another ArrayObject

When "foo" = [] I get an array object that I can call toArray to get the underlying value
When "foo" = "bar" my code tries to call toArray and fails

/**
 * @return Generator
 */
function getArrayObject() {
    // foo is string
    yield ArrayObject::fromArray([
        'foo' => 'bar',
    ]);

    // foo is array
    yield ArrayObject::fromArray([
        'foo' => [
            'bar',
        ],
    ]);
}

foreach (getArrayObject() as $arrayObject) {
    $arrayObject->get('foo')->toArray();
}

Fatal error: Uncaught Error: Call to a member function toArray() on string

Suggestions:

  • make "unbox" static so I can use something like this
ArrayObject::unbox($arrayObject->get('foo'));
  • Add a get function that doesn't box
$arrayObject->getRaw('foo');
  • Add a third flags param to get
// bitwise is cool
$arrayObject->get('foo', null, ArrayObject::NO_BOX);

// or just bool but no more flags possible
$arrayObject->get('foo', null, false);

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions