>  기사  >  백엔드 개발  >  PHP의 메소드 오버로딩

PHP의 메소드 오버로딩

PHPz
PHPz원래의
2024-08-29 12:59:19721검색

메서드 오버로딩은 속성 오버로딩 이외의 오버로딩 유형 중 하나입니다. 해당 클래스 범위/범위 내에서 생성되지 않은 하나/여러 개의 동적 메서드를 생성하는 것입니다. PHP 메소드 오버로딩 개념은 적절한 목적에 맞게 지정된 매직 메소드를 트리거하는 데도 도움이 됩니다. 속성 오버로딩 개념 외에도 PHP 메서드의 오버로딩 개념은 객체와 정적 컨텍스트 모두에서 함수 호출/호출을 허용합니다. 기본적으로 OOP의 방식 중 하나입니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문:

Public _call (string $name1 , array $arguments1 ) : mixed
Public static _callStatic (string $name1 , array $arguments1 ) : mixed

PHP에서 메소드 오버로딩은 어떻게 작동하나요?

메서드 오버로딩은 동적 메서드를 생성하여 클래스 내부 선언과 함께 작동합니다. 또한 적절한 목적을 위해 일부 매직 메소드를 트리거하고 정적 컨텍스트와 객체 모두에서 함수/함수 호출을 호출하여 작동합니다. 메소드 오버로딩 개념은 c, java 등과 같은 대부분의 다른 프로그래밍 언어에도 적합합니다. 우리는 메소드 오버로딩을 정적 다형성이라고 부릅니다.

몇 가지 마법 기능은 다음과 같습니다.

  • _call(): 객체의 컨텍스트는 call() 함수를 사용하여 오버로드된 메서드의 실행을 트리거할 수 있습니다.
  • _callStatic(): callstatic() 매직 함수는 정적 컨텍스트에서 오버로드된 개념/메서드를 활성화합니다.

PHP의 메소드 오버로딩 예

아래에 언급된 PHP의 메소드 오버로딩 예는 다음과 같습니다

예시 #1

아래 PHP 프로그래밍 언어에서 $name1 인수는 호출할 메서드의 이름인 반면 $arguments는 $name'ed 메서드에 전달하는 데 사용되는 매개변수/인수를 포함하는 열거형 배열 중 하나입니다.

_call() 함수는 $name1 및 $arguments1 매개변수 2개를 사용하여 사용됩니다. Implode() 함수는 배열 요소, 즉 문자열/문장에서 문자열을 반환합니다. Implode(separator, array)에서 구분 기호는 선택적 매개 변수이지만 이전 버전과의 호환성을 위해 두 매개 변수를 모두 사용하는 것이 좋습니다. 구분 기호 매개변수의 특정 유형의 구분 기호는 배열 매개변수에 있는 단어/문자열에 구분 기호를 삽입합니다.

Obj 변수는 SPK라는 새 개체를 생성합니다. Obj-> 객체의 메서드와 속성에 액세스하는 데 도움이 됩니다. Spk는 정적 컨텍스트에서 실행되는 반면 obj는 객체 컨텍스트에서 실행됩니다.

코드:

<?php
class SPK {
public function __call($name1, $arguments1) {
echo "object method calling '$name1' "
. implode(', ', $arguments1). "\n";
}
public static function __callStatic($name1, $arguments1) {
echo "static method Calling '$name1' "
. implode(', ', $arguments1). "\n";
}
}
// Create new object
$obj = new SPK;
$obj->runTest('in one of the object context');
SPK::runTest('in one of the static context');
?>

출력:

PHP의 메소드 오버로딩

예시 #2

코드 예제에서는 메시지를 표시하고 현재 PHP 스크립트를 종료하기 위해 die() 함수를 실행하는 단일 _call() 함수로 foo1 클래스를 정의합니다. Die()는 괄호 안에 하나의 매개변수만 허용하는 exit() 함수와 동일합니다.

Foo1-> $foo1 변수에서 개체의 메서드와 속성에 액세스하는 데 도움이 됩니다.

코드:

<?php
class Foo1 {
function __call($m1, $a1) {
die($m1);
}
}
$foo1 = new Foo1;
print $foo1->{' wow !'}();
// outputs ' wow !'
?>

출력:

PHP의 메소드 오버로딩

예시 #3

call() 함수와 프라이빗/보호 메서드를 사용하는 PHP 프로그래밍 언어의 메서드 오버로드 예입니다.

여기서 private/protected 메서드 호출은 오타 등으로 접근하여 이루어집니다.

Echo _METHOD_PHP_EOL은 사용된 메소드 유형을 반환합니다. 객체 컨텍스트에서 실행되는 _call() 함수만 사용합니다.

코드:

<?php
class TestMagicCallMethod1 {
public function foo1()
{
echo __METHOD__.PHP_EOL;
}
public function __call($method1, $args1)
{
echo __METHOD__.PHP_EOL;
if(method_exists($this, $method1))
{
$this->$method1();
}
}
protected function bar1()
{
echo __METHOD__.PHP_EOL;
}
private function baz1()
{
echo __METHOD__.PHP_EOL;
}
}
$test    =    new TestMagicCallMethod1();
$test->foo1();
$test->bar1();
$test->baz1();
?>

출력:

PHP의 메소드 오버로딩

예시 #4

메서드 오버로딩 개념에 사용되는 call() 및 call static() 함수 개념의 프로그램입니다. 아래 PHP 프로그램은 먼저 인스턴스의 _callstatic() 함수보다 먼저 _call() 함수를 호출합니다.

Var dump()는 PHP 및 일부 다른 객체 지향 프로그래밍 언어에서 괄호 안의 변수에 대한 정보를 제공합니다. 그 외에는 위 예시와 동일합니다.

코드:

<?php
class A1 {
public function test1 () {
static::who();
A1::who();
self::who();
$this->who();
}
public static function __callStatic($a1, $b1) {
var_dump('A1 static');
}
public function __call($a1, $b1) {
var_dump('A1 call');
}
}
$a1 = new A1;
$a1->test1();
?>

출력:

PHP의 메소드 오버로딩

예시 #5

이것은 _call() 함수의 예입니다. 존재하지도 않는 메소드를 사용하여 객체의 클래스를 호출하면 해당 메소드 대신 _call() 함수의 개념이 호출됩니다.

Execute the _call() function to support the concept of method overloading through the dynamic area() method included in the PHP program below. The object’s behavior will vary depending on the parameters that pass to it.

Code:

<?php
class Shape1 {
const PI1 = 3.142 ;
function __call($name1,$arg1){
if($name1 == 'area1')
switch(count($arg1)){
case 0 : return 0 ;
case 1 : return self::PI1 * $arg1[0] ;
case 2 : return $arg1[0] * $arg1[1];
}
}
}
$circle1 = new Shape1();
echo $circle1->area1(3);
$rect1 = new Shape1();
echo $rect1->area1(8,6);
?>

Output:

PHP의 메소드 오버로딩

Example #6

Here, the _call() and _callstatic() functions are used like in the 1st example.

Code:

<?php
class Toys1
{
public function __call($name1,$pavan1){
echo "Magic method invoked while method overloading with object reference";
}
public static function __callStatic($name1,$pavan1){
echo "Magic method invoked while method overloading with static access";
}
}
$objToys1 = new Toys1;
$objToys1->overloaded_method();
Toys1::overloaded_property();
?>

Output:

PHP의 메소드 오버로딩

Example #7

The call () function of method Overloading triggered and invoked the inaccessible methods in the object context. Call() is mixed with the syntax _call(string $name1 , array $arguments1).

Then $name1 parameter is for the name of the method which is to be called, whereas the array $arguments1 is the parameter that is an enumerated array that contains/has the parameters which are to be passed to the $name variables method.

Code:

<?php
class ABC1 {
public function __call($method_name1, $arguments1) {
$methodArray1 = array('displayMessage11','displayMessage12');
if (in_array($method_name1,$methodArray1) === false) {
die("\n Method does not exist");
}
if (count($arguments1) === 2) {
$this->displayMessage12($arguments1[0],$arguments1[1]);
}
elseif (count($arguments1) === 1) {
$this->displayMessage11($arguments1[0]);
} else {
echo "\n unknown method";
return false;
}
}
function displayMessage11($var11) {
echo "\n from func1($var11)";
}
function displayMessage12($var11,$var12) {
echo "\n from func2($var11,$var12)";
}
}
$obj1 = new ABC1;
$obj1->displayMessage11('hello');
$obj1->displayMessage12('hello','hello2');
$obj1->displayMessage13('Hello');
?>

Output:

PHP의 메소드 오버로딩

Example #8

It is also just like the first example program. Check it once.

Code:

<?php
class MethodOverloading1
{
public function __call($name1,$pavan1){
echo "\n--It is now With the object reference ";
}
public static function __callStatic($name1,$pavan1){
echo "\n-----It is now With the static reference \n";
}
}
// Here now creating the object of the class " MethodOverloading "
$obj1 = new MethodOverloading1;
echo "Method Overloading1 Now in Command ";
// Now using the object's reference
$obj1->DemoTest1();
// Now using the static's reference
MethodOverloading1::DemoTest1();
?>

Output:

PHP의 메소드 오버로딩

Example #9

This program shows the area of the circle and rectangle using some parameters and the call() function of the method overloading concept. The program will only run with the object context due to the object assigning an object variable to the class, etc.

Code:

<?php
class TDshape1 {
const Pi1 = 3.142 ;  // constant value
function __call($fname1, $argument1){
if($fname1 == 'area1')
switch(count($argument1)){
case 0 : return 0 ;
case 1 : return self::Pi1 * $argument1[0] ; // 3.14 * 15
case 2 : return $argument1[0] * $argument1[1];  // 5 * 11
}
}
}
$circle1 = new TDshape1();
echo "Area of the circle:".$circle1->area1(15); // display output of the area of circle
$rect1 = new TDshape1();
echo "\n Area of the rectangle:".$rect1->area1(5,11); // display output of the area of rectangle
?>

Output:

PHP의 메소드 오버로딩

위 내용은 PHP의 메소드 오버로딩의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP에서 재정의다음 기사:PHP에서 재정의