php 使用 __call实现重载功能示例

yipeiwu_com6年前PHP基础知识

本文实例讲述了php 使用 __call实现重载功能。分享给大家供大家参考,具体如下:

<?php
/**
 * Created by PhpStorm.
 * User: funco
 * Date: 17-6-9
 * Time: 下午1:39
 */
class MulStat
{
  // showClass 可以接受0个参数
  private function showClass() {
    echo "this is class ".__CLASS__;
  }

  // showString 可以接受一个参数
  private function showString($str) {
    echo "string is ".$str;
  }

  // __call方法 可以获取实例化对象调用的成员函数名和向该被调函数传递的参数个数
  public function __call($name, $args) {
    // 先判断要调用的函数名$name
    if($name == "showInfo"){
      // 然后可以根据参数($args)数量判断调用哪个成员函数
      switch(count($args)) {           // count可以计算数组元素个数
        case 0:
          $this->showClass();break;
        case 1:
          $this->showString($args[0]);break;
      }// switch
    }// if
  }
}

//实例化MulStat类
$mulStat = new MulStat();

echo "\$mulStat->showInfo(\"funco 小风\"):\n";
$mulStat->showInfo("funco 小风");

// 两次换行 便于观察结果
echo "\n\n";

echo "\$mulStat->showInfo():\n";
$mulStat->showInfo();

运行结果:

$mulStat->showInfo("funco 小风"):
string is funco 小风

$mulStat->showInfo():
this is class MulStat

相关文章

PHP实现文件分片上传的实例代码

PHP实现文件分片上传的实例代码

PHP用超级全局变量数组$_FILES来记录文件上传相关信息的。1.file_uploads=on/off是否允许通过http方式上传文件2.max_execution_time=30允许脚本最大执行...

PHP高并发和大流量解决方案整理

一、高并发的概念在互联网时代,并发,高并发通常是指并发访问。也就是在某个时间点,有多少个访问同时到来。二、高并发架构相关概念1、QPS (每秒查询率) : 每秒钟请求或者查询的数量,在互联...

echo(),print(),print_r()之间的区别?

echo是PHP语句, print和print_r是函数,语句没有返回值,函数可以有返回值(即便没有用)   print只能打印出简单类型变量的值(如int,strin...

PHP 常见郁闷问题答解

在register_global默认为off 若想取得从另一页面提交的变量: 方法一:在PHP.ini中找到register_global,并把它设置为on. 方法二:在接收网页最...

php 多继承的几种常见实现方法示例

本文实例讲述了php 多继承的几种常见实现方法。分享给大家供大家参考,具体如下:class Parent1 {   function m...