PHP5面向对象类属性与方法的调用。

类:

class Test {
  public $name = 'vilay';
	private $age;
	public function mtest()
	{
	  echo 'hello world';
	}
}

调用方式:

$test = new Test();
$test->name;
echo '<br>';
$test->mtest();

结果:

vilay
hello world

如果我们不小心调用类中不可访问的属性时,比如

$test = new Test();
$test->age = 21
echo $test->age;

则会报错,未定义的类属性:

Fatal error: Uncaught Error: Cannot access private property Test::$age

在PHP5中定义了__set,__get魔术方法处理类中不可访问 或者未定义的__属性__。

修改后的类:

class Test {
  public $name = 'vilay';
  private $age;
  public function mtest()
  {
      echo 'hello world';
  }

  public function __set($name,$value)
  {
      $this->$name = $value;
  }

  public function __get($name)
  {
      return $this->$name;
  }
}

再次执行php文件,结果:

21

在给__不可访问__或者__未定义的属性__赋值的时候会调用__set方法

在访问__不可访问__或者__未定义的属性__的时候会调用__get方法

如果无意中调用了未申明或者不可访问的__方法__:

$test = new Test();
$test->getList();

结果:

Fatal error: Uncaught Error: Call to undefined method Test::getList() in

PHP5中定义了__call方法,在调用未申明或者不可访问的__方法__时调用。

修改后的类:

class Test {
  public $name = 'vilay';
  private $age;
  public function mtest()
  {
      echo 'hello world';
  

  public function __set($name,$value)
  {
      $this->$name = $value;
  }

  public function __get($name)
  {
      return $this->$name;
  }

  public function __call($method_name,$args)
  {
      echo 'method is: '.$method_name.' arguments is:'.implode(',',$args);
  }

}

再次执行代码,由于未定义过getList()方法,自动调用__call方法:

method is: getList arguments is:

还有__callStatic方法,原理与__call一致,只是针对的是静态方法。

__invoke

在PHP5.3之后,定义了 __invoke 魔术方法。当尝试以调用函数的方式调用一个对象时,__invoke() 方法会被自动调用

代码示例:

<?php 
class Testinvoke {
		public function __invoke($a)
		{
				var_dump($a);
		}
}

$test = new Testinvoke;
$test(5);
var_dump(is_callable($test));

输出:

int(5) bool(true)