PHP는 객체 지향 매직 메소드의 __call 함수를 사용합니다. 1. 액세스할 수 없는 멤버 메소드가 호출되면 [__call] 매직 메소드가 호출됩니다. 2. 멤버 메소드가 존재하지 않고 멤버 메소드가 보호됩니다. private 언제, [__call] 매직 메서드를 호출합니다.

PHP는 객체 지향 매직 메서드의 __call 함수를 사용합니다.
기본 소개:
(1) 액세스할 수 없는 멤버 메서드를 조정할 때 __call 매직 메서드는 Call이 됩니다.
(2) 액세스할 수 없는 멤버 메서드는 (1. 멤버 메서드가 존재하지 않음, 2. 멤버 메서드가 protected 또는 private임)을 참조하세요.
Requirements
클래스 외부에서 직접 액세스할 수 있기를 바랍니다. 회원 메소드(비공개, 보호).
사례 설명
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <?php
header('content-type:text/html;charset=utf-8');
class Monk{
public $name ;
protected $hobby ;
public function __construct( $name , $hobby ){
$this ->name = $name ;
$this ->hobby = $hobby ;
}
public function showInfo(){
echo '<br> 名字是 ' . $this ->name;
foreach ( $this ->hobby as $hobby ){
echo '<br> 爱好有 ' . $hobby ;
}
}
protected function getSum( $num1 , $num2 ){
return $num1 + $num2 ;
}
public function __call( $method_name , $parameters ){
if (method_exists( $this , $method_name )){
return $this -> $method_name ( $parameters [0], $parameters [1]);
} else {
return '没有你要调用的函数';
}
}
}
$monk = new Monk('济公', array ('no1'=>'腾云驾雾', 'no2'=>'喝酒'));
$monk ->showInfo();
echo '<br> 结果是' . $monk ->getSum(100, 200);
|
로그인 후 복사
연습 질문:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <?php
header('content-type:text/html;charset=utf-8');
class Cat{
public $name ;
public $age ;
public function __construct( $name , $age ){
$this ->name = $name ;
$this ->age = $age ;
}
private function jiSuan( $n1 , $n2 , $oper ){
$res = 0;
switch ( $oper ){
case '+':
$res = $n1 + $n2 ;
break ;
case '-':
$res = $n1 - $n2 ;
break ;
case '*':
$res = $n1 * $n2 ;
break ;
case '/':
$res = $n1 / $n2 ;
break ;
default :
echo '你输入的运算符号不对';
}
return $res ;
}
public function __call( $method_name , $parameters ){
if ( $method_name == 'play'){
if ( method_exists( $this , $parameters [0]) ){
return $this -> $parameters [0]( $parameters [1], $parameters [2], $parameters [3]);
} else {
return ' 你调用的 ' . $parameters [0] . ' 不存在';
}
} else {
return ' 你调用的方式有问题 ';
}
}
}
$cat = new Cat('小花猫', 3);
echo '<br> 运算的结果是 ' . $cat ->play('jiSuan', 10, 20, '-');
|
로그인 후 복사
위 내용은 PHP에서 객체지향 매직 메소드인 __call 함수를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!