当前位置: 首页> 最新文章列表> PHP 重载基础知识概述与应用解析

PHP 重载基础知识概述与应用解析

gitbox 2025-06-28

什么是PHP重载

PHP是一种动态类型语言,意味着变量在脚本执行时不需要预定义类型,同时函数也可以没有参数类型或返回类型。PHP重载指的是在运行时动态创建或修改类的属性和方法。

PHP支持两种主要的重载形式:

1. 属性重载:通过魔术方法 __get()__set(),可以动态地访问或设置类的属性。

2. 方法重载:通过魔术方法 __call()__callStatic(),可以动态地调用类的方法。

属性重载

__get()方法

当访问一个不存在的属性时,__get() 方法会被调用。通过该魔术方法,可以动态添加属性。


class Test {
  private $data = [
    'name' => 'Tom',
    'age' => 18
  ];

  public function __get($name) {
    if (isset($this->data[$name])) {
      return $this->data[$name];
    }
    return null;
  }
}

$test = new Test();
echo $test->name;  // 输出 Tom
echo $test->age;   // 输出 18
echo $test->gender;  // 输出 null

__get() 方法接受一个参数 $name,即属性名。如果该属性不存在,则返回 null

__set()方法

当给一个不存在的属性赋值时,__set() 方法会被触发。通过该魔术方法,可以动态地添加一个属性及其值。


class Test {
  private $data = [];

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

$test = new Test();
$test->name = 'Tom';
echo $test->name;  // 输出 Tom

__set() 方法接受两个参数:$name(属性名)和 $value(属性值)。

方法重载

__call()方法

当调用一个不存在的方法时,__call() 方法会被调用。通过该魔术方法,可以动态地添加方法。


class Test {
  public function __call($name, $arguments) {
    if ($name == 'add') {
      return array_sum($arguments);
    }
    return null;
  }
}

$test = new Test();
echo $test->add(1, 2, 3);  // 输出 6
echo $test->subtract(10, 2);  // 输出 null

__call() 方法接受两个参数:$name(方法名)和 $arguments(方法参数)。如果该方法不存在,则返回 null

__callStatic()方法

当调用一个不存在的静态方法时,__callStatic() 方法会被调用。该方法与 __call() 方法类似,只不过它用于静态方法。


class Test {
  public static function __callStatic($name, $arguments) {
    if ($name == 'add') {
      return array_sum($arguments);
    }
    return null;
  }
}

echo Test::add(1, 2, 3);  // 输出 6
echo Test::subtract(10, 2);  // 输出 null

__callStatic() 方法与 __call() 方法类似,但只适用于静态方法。