0

is there a way to pass an array to a member function? i tried this code:

class Testing
{
   public function set($arr)
   { 
      echo $arr['key'];
   }
}

but i got this error: Undefined index (key)

4
  • is $arr['key'] defined? Commented Oct 11, 2011 at 9:16
  • Where are you calling the set method from ? if you pass it an array that has the a key of key then it will work ..... maybe I misread the question ? Commented Oct 11, 2011 at 9:16
  • Does the array you passed has the index key? Commented Oct 11, 2011 at 9:16
  • you all were right, the problem was- no index key. Commented Oct 11, 2011 at 9:31

2 Answers 2

4

You can pass an array, just like how you have done.

The problem is, the array you passed does not have a member with the a key of key.

You can enforce passing an array by placing a preceding Array before the argument in the argument signature.

public function set(Array $arr) { ... } 

You can also check for an array key being set with isset() or array_key_exists(), the latter which works with keys with the NULL value.

Sign up to request clarification or add additional context in comments.

Comments

1

You pass an array to a method, like you pass any other type to a method

$o = new Testing;
$array = array('key' => 'Hello World');
$o->set($array);

In your case it seems, that your array is just invalid (=> it doesn't have a key named "key").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.