Jump to content

Differences in method writing


dennismonsewicz

Recommended Posts

Can someone explain the difference between the following?

 

function a(array $var) { }

 

function a($var = array()) { }

 

function a(Array $var) { }

 

I have seen these recently in a script I am modifying, but not 100% sure as to what each one does. Well I know what the middle one does, but am a little confused on the 1st and 3rd one.

 

Thanks!

Dennis

Link to comment
Share on other sites

array and Array are the same, it's case insensitive.  So 1 and 3 are the same.

 

function a(array $var) { }

 

This says that a() MUST take an array, and it's an error if you give it something else.

 

"Catchable fatal error: Argument 1 passed to a() must be an array, string given"

Link to comment
Share on other sites

array and Array are the same, it's case insensitive.  So 1 and 3 are the same.

 

function a(array $var) { }

 

This says that a() MUST take an array, and it's an error if you give it something else.

 

"Catchable fatal error: Argument 1 passed to a() must be an array, string given"

 

Ah that makes sense! So my 2nd example is stating the $var could be an array, right?

Link to comment
Share on other sites

array and Array are the same, it's case insensitive.  So 1 and 3 are the same.

 

function a(array $var) { }

 

This says that a() MUST take an array, and it's an error if you give it something else.

 

"Catchable fatal error: Argument 1 passed to a() must be an array, string given"

 

Ah that makes sense! So my 2nd example is stating the $var could be an array, right?

 

The second example says that if no argument is passed to the method, $var will be an empty array by default.  Otherwise, it will be whatever you passed to the method.

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.