PHP 함수 오버로드

C++ 배경에서 작성됩니다.
PHP 기능을 오버로드하려면 어떻게 해야 하나요?

인수가 있는 경우 함수 정의 중 하나와 인수가 없는 경우 함수 정의 중 하나입니까?PHP로 가능한가요?아니면 $_GET과 POST에서 전달된 파라미터가 있는지 확인하기 위해 다른 것을 사용해야 합니까?연관지을 수 있을까요?



질문에 대한 답변



PHP 함수는 오버로드할 수 없습니다.함수 시그니처는 이름만을 기반으로 하며 인수 목록을 포함하지 않으므로 같은 이름의 함수를 2개 사용할 수 없습니다.클래스 메서드 오버로드는 PHP에서 다른 많은 언어와 다릅니다.PHP는 같은 단어를 사용하지만 다른 패턴을 나타냅니다.

단, 변수 개수의 인수를 사용하는 바리에타드 함수를 선언할 수 있습니다.인수를 전달받으려면 및 을 사용하여 정상적으로 인수를 사용합니다.

예를 들어 다음과 같습니다.

function myFunc() {
for ($i = 0; $i < func_num_args(); $i++) {
printf("Argument %d: %sn", $i, func_get_arg($i));
} }
/* Argument 0: a Argument 1: 2 Argument 2: 3.5 */ myFunc('a', 2, 3.5); 



PHP는 기존의 메서드 오버로드를 지원하지 않지만 원하는 것을 달성할 수 있는 한 가지 방법은__call매직 메서드:

class MyClass {
public function __call($name, $args) {
switch ($name) {
 case 'funcOne':

switch (count($args)) {

case 1:

 return call_user_func_array(array($this, 'funcOneWithOneArg'), $args);

case 3:

 return call_user_func_array(array($this, 'funcOneWithThreeArgs'), $args);

}
 case 'anotherFunc':

switch (count($args)) {

case 0:

 return $this->anotherFuncWithNoArgs();

case 5:

 return call_user_func_array(array($this, 'anotherFuncWithMoreArgs'), $args);

}
}
}
protected function funcOneWithOneArg($a) {
}
protected function funcOneWithThreeArgs($a, $b, $c) {
}
protected function anotherFuncWithNoArgs() {
}
protected function anotherFuncWithMoreArgs($a, $b, $c, $d, $e) {
}
} 



함수를 오버로드하려면 기본적으로 null로 pass 파라미터를 수행합니다.

class ParentClass {
function mymethod($arg1 = null, $arg2 = null, $arg3 = null)
{
if( $arg1 == null && $arg2 == null && $arg3 == null ){
 return 'function has got zero parameters <br />';
}
else
{
$str = '';
if( $arg1 != null )

$str .= "arg1 = ".$arg1." <br />";
 if( $arg2 != null )

$str .= "arg2 = ".$arg2." <br />";
 if( $arg3 != null )

$str .= "arg3 = ".$arg3." <br />";
 return $str;
}
} }
// and call it in order given below ...
$obj = new ParentClass;
echo '<br />$obj->mymethod()<br />';
echo $obj->mymethod();
echo '<br />$obj->mymethod(null,"test") <br />';
echo $obj->mymethod(null,'test');
echo '<br /> $obj->mymethod("test","test","test")<br />';
echo $obj->mymethod('test','test','test'); 



<?php
/*******************************
* author
: hishamdalal@gmail.com
* version : 3.8
* create on : 2017-09-17
* updated on : 2020-01-12
* download example:
https://github.com/hishamdalal/overloadable
*****************************/
#> 1. Include Overloadable class
class Overloadable {
static function call($obj, $method, $params=null) {
$class = get_class($obj);
// Get real method name
$suffix_method_name = $method.self::getMethodSuffix($method, $params);
if (method_exists($obj, $suffix_method_name)) {
 // Call method
 return call_user_func_array(array($obj, $suffix_method_name), $params);
}else{
 throw new Exception('Tried to call unknown method '.$class.'::'.$suffix_method_name);
}
}
static function getMethodSuffix($method, $params_ary=array()) {
$c = '__';
if(is_array($params_ary)){
 foreach($params_ary as $i=>$param){

// Adding special characters to the end of method name

switch(gettype($param)){

case 'array':
$c .= 'a'; break;

case 'boolean':
$c .= 'b'; break;

case 'double':
$c .= 'd'; break;

case 'integer':
$c .= 'i'; break;

case 'NULL':
$c .= 'n'; break;

case 'object':

 // Support closure parameter

 if($param instanceof Closure ){


$c .= 'c';

 }else{


$c .= 'o';


}

break;

case 'resource':
$c .= 'r'; break;

case 'string':
$c .= 's'; break;

case 'unknown type':$c .= 'u'; break;

}
 }
}
return $c;
}
// Get a reference variable by name
static function &refAccess($var_name) {
$r =& $GLOBALS["$var_name"];
return $r;
} } //---------------------------------------------------------- #> 2. create new class //----------------------------------------------------------
class test
{
private $name = 'test-1';
#> 3. Add __call 'magic method' to your class
// Call Overloadable class
// you must copy this method in your class to activate overloading
function __call($method, $args) {
return Overloadable::call($this, $method, $args);
}
#> 4. Add your methods with __ and arg type as one letter ie:(__i, __s, __is) and so on.
#> methodname__i = methodname($integer)
#> methodname__s = methodname($string)
#> methodname__is = methodname($integer, $string)
// func(void)
function func__() {
pre('func(void)', __function__);
}
// func(integer)
function func__i($int) {
pre('func(integer '.$int.')', __function__);
}
// func(string)
function func__s($string) {
pre('func(string '.$string.')', __function__);
}
// func(string, object)
function func__so($string, $object) {
pre('func(string '.$string.', '.print_r($object, 1).')', __function__);
//pre($object, 'Object: ');
}
// func(closure)
function func__c(Closure $callback) {

pre("func(".
 print_r(

array( $callback, $callback($this->name) ),

1
 ).");", __function__.'(Closure)'
);

}
// anotherFunction(array)
function anotherFunction__a($array) {
pre('anotherFunction('.print_r($array, 1).')', __function__);
$array[0]++;
// change the reference value
$array['val']++;
// change the reference value
}
// anotherFunction(string)
function anotherFunction__s($key) {
pre('anotherFunction(string '.$key.')', __function__);
// Get a reference
$a2 =& Overloadable::refAccess($key); // $a2 =& $GLOBALS['val'];
$a2 *= 3;
// change the reference value
}
}
//---------------------------------------------------------- // Some data to work with: $val
= 10; class obj {
private $x=10; }
//---------------------------------------------------------- #> 5. create your object
// Start $t = new test;
#> 6. Call your method
// Call first method with no args: $t->func();
// Output: func(void)
$t->func($val); // Output: func(integer 10)
$t->func("hello"); // Output: func(string hello)
$t->func("str", new obj()); /* Output:
func(string str, obj Object (
[x:obj:private] => 10 ) ) */
// call method with closure function $t->func(function($n){
return strtoupper($n); });
/* Output: func(Array (
[0] => Closure Object
(
 [parameter] => Array

(

[$n] =>

)
)
[1] => TEST-1 ) ); */
## Passing by Reference:
echo '<br><br>$val='.$val; // Output: $val=10
$t->anotherFunction(array(&$val, 'val'=>&$val)); /* Output: anotherFunction(Array (
[0] => 10
[val] => 10 ) ) */
echo 'Result: $val='.$val; // Output: $val=12
$t->anotherFunction('val'); // Output: anotherFunction(string val)
echo 'Result: $val='.$val; // Output: $val=36
// Helper function //---------------------------------------------------------- function pre($mixed, $title=null){
$output = "<fieldset>";
$output .= $title ? "<legend><h2>$title</h2></legend>" : "";
$output .= '<pre>'. print_r($mixed, 1). '</pre>';
$output .= "</fieldset>";
echo $output; } //---------------------------------------------------------- 



어떤 사람들에게는 해킹이지만, 저는 Cakephp가 어떤 기능을 하는 것을 보고 이 방법을 배웠고, 그것이 만들어내는 유연성이 좋아서 그것을 적응시켰습니다.

즉, 다른 유형의 인수, 배열, 객체 등을 가진 후 전달된 항목을 감지하고 거기에서 이동합니다.

function($arg1, $lastname) {
if(is_array($arg1)){
$lastname = $arg1['lastname'];
$firstname = $arg1['firstname'];
} else {
$firstname = $arg1;
}
... }