0

I am dealing with an object of a class that I did not write and cannot change.This class has a very large number of attributes. I want to cycle trough about half of these attributes (a select group). I put the names of the nescessary attributes into an array and would like to cycle through them. Is this possible? What is the syntax like?

class B{
   public $foo = 'hi';
   public $bar = 'bye';
   ...etc, etc.
}

$arr = array(1=>'foo', 2=>'bar', ...)
$b = new B();
foreach($arr as $val){
  echo $b->($val); //<-----does not work
}
John R
  • 2,920
  • 13
  • 48
  • 62

4 Answers4

5

Yes you can. see the manual: http://php.net/manual/en/language.variables.variable.php

<?php
class foo {
    var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->$baz[1] . "\n";
?>

The above example will output:

I am bar.
I am bar
Nanne
  • 64,065
  • 16
  • 119
  • 163
1
echo $b->$val;

or method

echo $b->$val(params...);

and u can use one of the reflection functions to get all the methods and members

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
1

You were close:

$b->$val; //Or...
$b->{$val};
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

You can loop through each variable like this:

$b= new B();

foreach($b as $var => $value) {
    echo "$var is $value\n";
}
GDP
  • 8,109
  • 6
  • 45
  • 82