Jump to content

How do i pass array as an argument for a function ?


jd2007

Recommended Posts

<?php
class Arrays
{
private $arr=array();
private $mystr;

function produceStr(array $arr)
{
   $this->arr=$arr;
   $this->mystr=implode("and", $this->arr);
   echo $this->mystr;
}
}
?>

 

when i instantiate an object, i do this:

<?php
$a=new Arrays();
$b=array("a", "b", "c");
$a->produceStr($b);
?>

 

this doesn't work...why ?

Link to comment
Share on other sites

There is no object of type array in php so I don't believe you can type hint using it. eg; This...

 

function produceStr(array $arr)

 

should simply be...

 

function produceStr($arr)

 

Other than that, I don't really see any problem.

Link to comment
Share on other sites

Code works fine for me, using PHP5.2.x here. I noticed you are using the private keyword here for initiating variables. Make sure you are not using PHP4. PHP4 does not support the visibility keywords (private, protected and public), use var in replacement:

 var $arr=array();
var $mystr;

 

What results do you get?

 

EDIT: Didn't see the replies above

but i want to be array $arr but php treats it like string

Even if the you pass the produceStr function an array for the $arr argument $arr will still be an array, without 'array' before $arr.

Link to comment
Share on other sites

wildteen: You can use array for type hinting as well.

 

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

 

That was me. And thanks, something I was not aware of.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.