Looping Through All the Properties of Object PHP

Looping through all the properties of object php

If this is just for debugging output, you can use the following to see all the types and values as well.

var_dump($obj);

If you want more control over the output you can use this:

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

foreach on all object properties

Use Reflection class: Class Reflectionclass Manual ( PHP 5 )

<?php
class Foo {
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
print $prop->getName() . "\n";
}

var_dump($props);

?>

Running a loop through object properties and assign value

It doesn't work because of the double $$ when you assign the key:

$class->$$key = $arr[$i];

Change to a single $

$class->$key = $arr[$i];

Codepad demo

When accessing object properties without a variable, no $ is needed, therefore if your key is stored in a variable, a single $ is needed.

That said, there is likely a better way to solve the problem than this. Seems like the X Y Problem.

How to loop through objects in php

you dont need to convert them to anything.

foreach loop would work fine with you as follows in generic:

foreach ($objects as $obj) {
echo $obj->property;
}

for a inner object this would work:

foreach ($objects as $obj){
echo $obj->user->description;
}

Looping through objects then iterate through the object's property and value

Loop only first item to build the Table Header

<thead>

@foreach($stats->first() as $property => $value)

<th>
{{ $property }}
</th>

@endforeach

</thead>

iterate over properties of a php class

tl;dr

// iterate public vars of class instance $class
foreach (get_object_vars($class) as $prop_name => $prop_value) {
echo "$prop_name: $prop_value\n";
}

Further Example:

http://php.net/get_object_vars

Gets the accessible non-static properties of the given object according to scope.

class foo {
private $a;
public $b = 1;
public $c;
private $d;
static $e; // statics never returned

public function test() {
var_dump(get_object_vars($this)); // private's will show
}
}

$test = new foo;

var_dump(get_object_vars($test)); // private's won't show

$test->test();

Output:

array(2) {
["b"]=> int(1)
["c"]=> NULL
}

array(4) {
["a"]=> NULL
["b"]=> int(1)
["c"]=> NULL
["d"]=> NULL
}

looping through object in PHP

You have here Laravel's Collection object. Read about collections here and use one of it's methods like map, filter, each ...

For example, you can try:

$collection->each(function ($item, $key) {
if ((32 & $item->permissions) !== 0) {
// do something
}
});

Iterate through an object's properties and modify the original object

Try this:

foreach ($class as $key => $value) {
if (empty($value)) {
$value = 'something';
$class->$key = $value;
}
}


Related Topics



Leave a reply



Submit