1
class A {
  public $a;
  public $b;

  function f1 () {
     // Code
  }
}

$obj = new A();

$arr = array ("a" => 1, "b" => 2);

foreach ($arr as $name => $value) {
  $obj->$name = $value;
}

return $obj;

I am not able to understand foreach section. How can we pass array as object and fetch that data as array?

jkdev
  • 11,360
  • 15
  • 54
  • 77
Avish Shah
  • 23
  • 5
  • 1
    Hi, this might help [How foreach works](https://stackoverflow.com/questions/10057671/how-does-php-foreach-actually-work) – Roshan Feb 06 '19 at 07:16
  • i know about foreach, but question is how can we store value for variable and returning that as object and that object behave as array? – Avish Shah Feb 06 '19 at 07:22
  • "Pass array as object" where? – u_mulder Feb 06 '19 at 07:22
  • 1
    It's not a very good example of [variable variables](https://stackoverflow.com/questions/12571197/how-do-i-dynamically-write-a-php-object-property-name), it's using `$arr` (an array) to set the properties of `$obj` (an object) and returning the object. – Nigel Ren Feb 06 '19 at 07:25
  • return $obj; when we return $obj; it passes a array right? if i am wrong just explain what it passes. – Avish Shah Feb 06 '19 at 07:31
  • `$obj` is an __object__ of class A. – u_mulder Feb 06 '19 at 07:35

2 Answers2

2

Explanation of your foreach loop:

  1. Each loop you get key name of array and value of array element
  2. Than you set $obj property here $obj->$name = $value;
  3. $name is replaced with array key name therefore it looks like $obj->a = $value;

To pass array to object, use magic setter method:

class A {
  public $a;
  public $b;

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}

$obj = new A();

$arr = array ("a" => 1, "b" => 2);

foreach ($arr as $name => $value) {
  $obj->__set($name, $value);
}

All of the object are as array automatically, so to fetch it back as array, you can loop object directly:

foreach ($obj as $key => $value) {
  print "$key => $value\n";
}

To get directly full array from object you can make another method which will do this for you:

public function getAsArray() {
   $arr = array();
   foreach ($this as $key => $value) {
       $arr[$key] = $value;
   }

   return $arr;
}
MatejG
  • 1,393
  • 1
  • 17
  • 26
1

You can please check below code.

class A {
  public $a;
  public $b;

  function f1 () {
     // Code
  }
}

$obj = new A();
$arr = array ("a" => 1, "b" => 2);
foreach ($arr as $name => $value) {
  $obj->$name = $value;
}

return $obj;
// This return obj output is :-
A Object
(
    [a] => 1
    [b] => 2
)

Update your code with below code your will get array.

return (array)$obj;
//Output 

Array
(
    [a] => 1
    [b] => 2
)
Praveen Kumar
  • 864
  • 2
  • 9
  • 33