PHP에서 함수 오버로드 및 오버라이드는 무엇입니까?
PHP에서 함수 오버로드와 함수 오버라이드는 무엇을 의미합니까? 그리고 둘 사이의 차이점은 무엇입니까? 그들 사이의 차이점을 알 수 없었습니다.
오버로딩 은 비슷한 시그니처는 있지만 다른 매개 변수를 가진 함수를 정의합니다. 재정의 는 부모 클래스가 메서드를 정의했으며 파생 클래스 가 해당 메서드 를 재정의 하려는 파생 클래스에만 해당됩니다 .
PHP에서는 magic 메소드 만 사용하여 메소드를 오버로드 할 수 있습니다 __call
.
재정의 의 예 :
<?php
class Foo {
function myFoo() {
return "Foo";
}
}
class Bar extends Foo {
function myFoo() {
return "Bar";
}
}
$foo = new Foo;
$bar = new Bar;
echo($foo->myFoo()); //"Foo"
echo($bar->myFoo()); //"Bar"
?>
함수 오버로딩은 다른 매개 변수 세트를 사용하여 동일한 함수 이름을 두 번 이상 정의 할 때 발생합니다. 예를 들면 다음과 같습니다.
class Addition {
function compute($first, $second) {
return $first+$second;
}
function compute($first, $second, $third) {
return $first+$second+$third;
}
}
위의 예에서 함수 compute
는 서로 다른 두 개의 매개 변수 시그니처로 오버로드됩니다. * PHP에서는 아직 지원되지 않습니다. 대안은 선택적 인수를 사용하는 것입니다.
class Addition {
function compute($first, $second, $third = 0) {
return $first+$second+$third;
}
}
클래스를 확장하고 부모 클래스에 존재했던 함수를 다시 작성할 때 함수 재정의가 발생합니다.
class Substraction extends Addition {
function compute($first, $second, $third = 0) {
return $first-$second-$third;
}
}
예를 들어에 compute
명시된 동작을 재정의합니다 Addition
.
엄밀히 말하면, 차이가 없습니다.
함수 재정의는 APD와 같은 PHP 확장으로 수행 할 수 있지만 더 이상 사용되지 않으며 afaik 최신 버전을 사용할 수 없습니다.
동적 타이핑으로 인해 PHP에서 함수 오버로드를 수행 할 수 없습니다. 즉, PHP에서는 변수를 특정 유형으로 "정의"하지 않습니다. 예:
$a=1;
$a='1';
$a=true;
$a=doSomething();
각 변수는 유형이 다르지만 실행 전에 유형을 알 수 있습니다 (4 번째 변수 참조). 다른 언어는 다음을 사용합니다.
int a=1;
String s="1";
bool a=true;
something a=doSomething();
마지막 예에서는 변수 유형을 강제로 설정해야합니다 (예 : 데이터 유형 "something"을 사용함).
PHP에서 함수 오버로딩이 불가능한 또 다른 "문제": PHP에는 func_get_args ()라는 함수가 있습니다.이 함수는 현재 인수의 배열을 반환합니다. 이제 다음 코드를 고려하십시오.
function hello($a){
print_r(func_get_args());
}
function hello($a,$a){
print_r(func_get_args());
}
hello('a');
hello('a','b');
두 함수가 어느 정도의 인수를 허용한다는 것을 고려하면 컴파일러는 어느 인수를 선택해야합니까?
마지막으로 위의 답변이 부분적으로 잘못된 이유를 지적하고자합니다. 함수 오버로드 / 오버라이드는 메소드 오버로드 / 오버라이드와 같지 않습니다 .
Where a method is like a function but specific to a class, in which case, PHP does allow overriding in classes, but again no overloading, due to language semantics.
To conclude, languages like Javascript allow overriding (but again, no overloading), however they may also show the difference between overriding a user function and a method:
/// Function Overriding ///
function a(){
alert('a');
}
a=function(){
alert('b');
}
a(); // shows popup with 'b'
/// Method Overriding ///
var a={
"a":function(){
alert('a');
}
}
a.a=function(){
alert('b');
}
a.a(); // shows popup with 'b'
Overloading Example
class overload {
public $name;
public function __construct($agr) {
$this->name = $agr;
}
public function __call($methodname, $agrument) {
if($methodname == 'sum2') {
if(count($agrument) == 2) {
$this->sum($agrument[0], $agrument[1]);
}
if(count($agrument) == 3) {
echo $this->sum1($agrument[0], $agrument[1], $agrument[2]);
}
}
}
public function sum($a, $b) {
return $a + $b;
}
public function sum1($a,$b,$c) {
return $a + $b + $c;
}
}
$object = new overload('Sum');
echo $object->sum2(1,2,3);
Although overloading paradigm is not fully supported by PHP the same (or very similar) effect can be achieved with default parameter(s) (as somebody mentioned before).
If you define your function like this:
function f($p=0)
{
if($p)
{
//implement functionality #1 here
}
else
{
//implement functionality #2 here
}
}
When you call this function like:
f();
you'll get one functionality (#1), but if you call it with parameter like:
f(1);
you'll get another functionality (#2). That's the effect of overloading - different functionality depending on function's input parameter(s).
I know, somebody will ask now what functionality one will get if he/she calls this function as f(0).
I would like to point out over here that Overloading in PHP has a completely different meaning as compared to other programming languages. A lot of people have said that overloading isnt supported in PHP and by the conventional definition of overloading, yes that functionality isnt explicitly available.
However, the correct definition of overloading in PHP is completely different.
In PHP overloading refers to dynamically creating properties and methods using magic methods like __set() and __get(). These overloading methods are invoked when interacting with methods or properties that are not accessible or not declared.
Here is a link from the PHP manual : http://www.php.net/manual/en/language.oop5.overloading.php
There are some differences between Function overloading & overriding though both contains the same function name.In overloading ,between the same name functions contain different type of argument or return type;Such as: "function add (int a,int b)" & "function add(float a,float b); Here the add() function is overloaded. In the case of overriding both the argument and function name are same.It generally found in inheritance or in traits.We have to follow some tactics to introduce, what function will execute now. So In overriding the programmer follows some tactics to execute the desired function where in the overloading the program can automatically identify the desired function...Thanks!
Overloading: In Real world, overloading means assigning some extra stuff to someone. As as in real world Overloading in PHP means calling extra functions. In other way You can say it have slimier function with different parameter.In PHP you can use overloading with magic functions e.g. __get, __set, __call etc.
Example of Overloading:
class Shape {
const Pi = 3.142 ; // constant value
function __call($functionname, $argument){
if($functionname == 'area')
switch(count($argument)){
case 0 : return 0 ;
case 1 : return self::Pi * $argument[0] ; // 3.14 * 5
case 2 : return $argument[0] * $argument[1]; // 5 * 10
}
}
}
$circle = new Shape();`enter code here`
echo "Area of circle:".$circle->area()."</br>"; // display the area of circle Output 0
echo "Area of circle:".$circle->area(5)."</br>"; // display the area of circle
$rect = new Shape();
echo "Area of rectangle:".$rect->area(5,10); // display area of rectangle
Overriding : In object oriented programming overriding is to replace parent method in child class.In overriding you can re-declare parent class method in child class. So, basically the purpose of overriding is to change the behavior of your parent class method.
Example of overriding :
class parent_class
{
public function text() //text() is a parent class method
{
echo "Hello!! everyone I am parent class text method"."</br>";
}
public function test()
{
echo "Hello!! I am second method of parent class"."</br>";
}
}
class child extends parent_class
{
public function text() // Text() parent class method which is override by child
class
{
echo "Hello!! Everyone i am child class";
}
}
$obj= new parent_class();
$obj->text(); // display the parent class method echo
$obj= new parent_class();
$obj->test();
$obj= new child();
$obj->text(); // display the child class method echo
Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.
PHP 5.x.x does not support overloading this is why PHP is not fully OOP.
참고URL : https://stackoverflow.com/questions/2994758/what-is-function-overloading-and-overriding-in-php
'IT story' 카테고리의 다른 글
OSX El Capitan : sudo pip install OSError : [Errno : 1] 작업이 허용되지 않습니다 (0) | 2020.07.06 |
---|---|
LINQ를 통해 컬렉션의 모든 요소에 기능 적용 (0) | 2020.07.06 |
jQuery 세트 라디오 버튼 (0) | 2020.07.06 |
동적 선택 필드 작성 (0) | 2020.07.05 |
잘못된 값을 가진 ASP.Net MVC Html.HiddenFor (0) | 2020.07.05 |