PDA

View Full Version : داشتن بیش از یک Method با نام یکسان



Jason.Bourne
سه شنبه 18 تیر 1392, 09:12 صبح
چطوری میتونم در یک کلاس بیش از یک متد داشته باشم که نام آنها یکسان باشد، اما آرگومان های آنها متفاوت باشد.
مانند زیر:


class A {
function print_name($first_name)
{
echo $first_name;
}

function print_name($first_name, $last_name)
{
echo $first_name . ' - ' . $last_name;
}
}

فرزند کوروش
سه شنبه 18 تیر 1392, 09:15 صبح
تا اونجایی که من میدونم همچین چیزی امکان نداره!!

Jason.Bourne
سه شنبه 18 تیر 1392, 09:17 صبح
اگر چنین چیزی در PHP امکان نداره (که فکر کنم در ++C و Java باشه) ؛ راه حل جایگزین چی هست؟

httplistener
سه شنبه 18 تیر 1392, 09:27 صبح
سلام


class A {

function print_name($first_name, $last_name="undefined")
{
if($last_name=="undefined")
echo $first_name;
else
echo $first_name . ' - ' . $last_name;
}
}

httplistener
سه شنبه 18 تیر 1392, 09:35 صبح
یک مثال دیگه :


//Function to find sum of n numbers:
function findSum() {
$sum = 0;
foreach (func_get_args() as $arg) {
$sum += $arg;
}
return $sum;
}

echo findSum(1, 2), '<br />'; //outputs 3
echo findSum(10, 2, 100), '<br />'; //outputs 112

httplistener
سه شنبه 18 تیر 1392, 09:38 صبح
//Function to add two numbers or to concatenate two strings:

function add() {
//cross check for exactly two parameters passed
//while calling this function
if (func_num_args() != 2) {
trigger_error('Expecting two arguments', E_USER_ERROR);
}

//getting two arguments
$args = func_get_args();
$arg1 = $args[0];
$arg2 = $args[1];

//check whether they are integers
if (is_int($arg1) && is_int($arg2)) {
//return sum of two numbers
return $arg1 + $arg2;
}

//check whether they are strings
if (is_string($arg1) && is_string($arg2)) {
//return concatenated string
return $arg1 . ' ' . $arg2;
}

trigger_error('Incorrect parameters passed', E_USER_ERROR);
}

echo add(10, 15), '<br />'; //outputs 25
echo add("Hello", "World"), '<br />'; //outputs Hello World

از اینجا (http://programmers.stackexchange.com/questions/165467/why-php-doesnt-support-function-overloading)

habibvafapour
سه شنبه 18 تیر 1392, 09:50 صبح
class you{
public $i;
function __construct(){
switch($i){
case 0 :
function habib(){echo"new1";}
break;
case 1 :
function habib(){echo"new12";}
break;
case 3 :
function habib(){echo"new123";}
break;
case 4 :
function habib(){echo"new1234";}
break;

}
}
}

MMSHFE
سه شنبه 18 تیر 1392, 09:50 صبح
http://php.net/manual/en/language.oop5.overloading.php