Does a PHP function variable allow either a string or an array of a template or anti-template?

From C # I'm used to overloading my methods with variable parameters. Since you cannot do this in PHP , I often create methods like the example below that takes a variable, then I check the type and act accordingly:

showLength('one');
showLength(array(
    'one',
    'two',
    'three'
));

function showLength($stringOrArray) {
    $arr = array();
    if(is_array($stringOrArray)) {
       $arr = $stringOrArray;
    } else if(is_string($stringOrArray)) {
       $arr[] = $stringOrArray;
    } else {
        //exception
    }
    foreach ($arr as $str) {
        echo strlen($str).'<br/>';
    }
}

output:

3
3
3
5
4

This gives me the same functionality as in C #, but it seems a bit messy, as if there was a better way.

Is this an acceptable way to overload methods in PHP (5.3) or is there a better way?

+5
source share
3 answers

, , , PHP. "" "" (docblock). , .

:

<?php
/**
  * Function used to assign roles to a user
  * @param int   $user_id The user id
  * @param mixed $role    Either a string name of the role 
  *                       or an array with string values
  *
  * @return bool on success/failure
  */ 
function addRole($user_id, $role) {
  if (!is_array($role)) {
    $role = array($role);
  }

  foreach($role as item) {
    Model::addRole($item);
  }

  return true;
}
+10

, PHP, , #, , , , - .

PHP , . str_replace().

+3

, , .

-; @Merijn, PHP . , , , , .

(array) - :

function printStuff($stuff)
{
    foreach((array) $stuff as $key => $value) {
        echo sprintf('%d : %s', $key, $value) . PHP_EOL;
    }
}

printStuff("foo");
// 0 : foo

printStuff(array("foo", "bar", "qux"));
// 0 : foo
// 1 : bar
// 2 : qux

$foo = (array) $foo; 1 $foo = array($foo);, , $foo , .



1 produces the desired results with scalars; objects give different results. Objects passed to the array will list the properties, so use discretion.

+3
source

All Articles