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
https://forums.phpfreaks.com/topic/214134-differences-in-method-writing/
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"

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?

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.

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.