PHP에서 __call()을 사용하는 방법

墨辰丷
풀어 주다: 2023-03-25 18:14:02
원래의
27169명이 탐색했습니다.

PHP5 객체에는 객체의 다른 메소드를 모니터링하는 데 사용되는 새로운 특수 메소드 __call()이 있습니다. 존재하지 않거나 권한이 제어되는 개체에 대해 메서드를 호출하려고 하면 __call 메서드가 자동으로 호출됩니다.

1. __call

<?php  
class foo {  
  function __call($name,$arguments) {  
    print("Did you call me? I&#39;m $name!");  
  }  
} $x = new foo();  
$x->doStuff();  
$x->fancy_stuff();  
?>
로그인 후 복사

2. __call을 사용하여 "오버로드" 작업을 구현합니다.

<?php  
class Magic {  
  function __call($name,$arguments) {  
    if($name==&#39;foo&#39;) {  
  if(is_int($arguments[0])) $this->foo_for_int($arguments[0]);  
  if(is_string($arguments[0])) $this->foo_for_string($arguments[0]);  
    }  
  }   private function foo_for_int($x) {  
    print("oh an int!");  
  }   private function foo_for_string($x) {  
    print("oh a string!");  
  }  
} $x = new Magic();  
$x->foo(3);  
$x->foo("3");  
?>
로그인 후 복사

3. _call 및 ___callStatic은 PHP 클래스의 기본 함수입니다. __call( ) 객체 컨텍스트에서 호출된 메서드에 액세스할 수 없으면 트리거됩니다.

__callStatic() 정적 컨텍스트에서 호출된 메서드에 액세스할 수 없으면 트리거됩니다.

<?php  
abstract class Obj  
{  
protected $property = array();  
  
abstract protected function show();  
  
public function __call($name,$value)  
{  
if(preg_match("/^set([a-z][a-z0-9]+)$/i",$name,$array))  
{  
$this->property[$array[1]] = $value[0];  
return;  
}  
elseif(preg_match("/^get([a-z][a-z0-9]+)$/i",$name,$array))  
{  
return $this->property[$array[1]];  
}  
else  
{  
exit("<br>;Bad function name &#39;$name&#39; ");  
}  
  
}  
}  
  
class User extends Obj  
{  
public function show()  
{  
print ("Username: ".$this->property[&#39;Username&#39;]."<br>;");  
//print ("Username: ".$this->getUsername()."<br>;");  
print ("Sex: ".$this->property[&#39;Sex&#39;]."<br>;");  
print ("Age: ".$this->property[&#39;Age&#39;]."<br>;");  
}  
}  
  
class Car extends Obj  
{  
public function show()  
{  
print ("Model: ".$this->property[&#39;Model&#39;]."<br>;");  
print ("Sum: ".$this->property[&#39;Number&#39;] * $this ->property[&#39;Price&#39;]."<br>;");  
}  
}  
  
$user = new User;  
$user ->setUsername("Anny");  
$user ->setSex("girl");  
$user ->setAge(20);  
$user ->show();  
  
print("<br>;<br>;");  
  
$car = new Car;  
$car ->setModel("BW600");  
$car ->setNumber(5);  
$car ->setPrice(40000);  
$car ->show();  
?>
로그인 후 복사
요약:

__call() 함수는 객체의 컨텍스트에서 호출된 메서드가 존재하지 않으면 __call()이 트리거되는 PHP 클래스의 기본 마법 함수입니다.


관련 권장 사항:

PHP에서 __call() 및 __callStatic()을 사용하는 방법

PHP에서 __call() 메서드를 사용하는 방법 및 오버로드 인스턴스 분석

php의 매직 메서드 자세한 설명 __get(), __set(), __call(), __callStatic() 및 정적 사용법

매직 메소드 __call() 예제에 대한 자세한 설명(php 고급 객체 지향 튜토리얼)

위 내용은 PHP에서 __call()을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!