PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 23, 2022

[FIXED] How to fix "Call to a member function xy on array" without using foreach?

 August 23, 2022     magento2, php     No comments   

Issue

I have an object inside an array stored in the variable $image

array(1) { [250]=> object(Magento\Framework\DataObject)#11025 (1) { ["_data":protected]=> array(26) { ["value_id"]=> string(3) "250" ["file"]=> string(58) "/i/n/insetktenschutz-doppeltuer-im-zargenrahmen_37_1_3.jpg"  ... } } }

If I try to return a value, e.g. file like this:

echo $image->getFile();

Then of course I get Fatal error: Uncaught Error: Call to a member function getFile() on array

So I tried to call it like this:

$image = $image[0];
echo $image->getFile();

But I get Exception #0 (Exception): Notice: Undefined offset: 0

So I tried to cast it to an object:

$image = (object) $image;
echo $image->getFile();

Now I get Fatal error: Uncaught Error: Call to undefined method stdClass::getFile()

Then I used a foreach:

foreach($image as $i) {
    echo $image->getFile();  // alternative: $image->getData('file')
}

and it works! Why does it work with foreach and how can I make it work without?


Solution

You can try with reset array function of PHP to get first element of array

$imageData = reset($image);
echo $imageData->getData("file");


Answered By - Khushbu
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing