Jump to content

Pass an Array to a Class


MasterACE14

Recommended Posts

Hello,

 

I'm sure I've missed the obvious on this one.

 

Say I have something like the following(nonsense example)...

$arr['random'] = "Hello"
class hey {
public function say_hi() {
   echo $arr['random'];
}
}

 

Obviously that doesn't work. But how would I get to use that array from 'outside' of the class, 'inside' of it without actually putting the array inside the class?

 

Thanks, Ace

Link to comment
https://forums.phpfreaks.com/topic/187798-pass-an-array-to-a-class/
Share on other sites

You can pass it to the individual method itself or to the constructor if you need it within more than one method.

 

class hey {
  public function say_hi($a) {
   echo $arr['random'];
  }
}
$arr['random'] = "Hello";
$h = new hey;
$h->say_hi($arr);

 

$arr['random'] = "Hello"
class hey {
  private $a;
  public function __construct(array $a) {
    $this->a = $a;
  }
  public function say_hi() {
   echo $this->a['random'];
  }
}
$arr['random'] = "Hello";
$h = new hey($arr);
$h->say_hi();

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.