php函数重载的替代方法--伪重载详解
作者:hebedich 时间:2023-11-18 10:24:06
函数重载的替代方法-伪重载,下面看一个具体的实例代码。
<? php
//函数重载的替代方法-伪重载
//
//确实,在PHP中没有函数重载这个概念,让很多时候我们无法进行一些处理,甚至有时候不得不在函数后面定义好N个参数
//在看到了func_get_arg,func_get_args,func_num_args,这三个函数的时候,你们是不是想起了什么?
function testOne ( $a ) {
echo (' 一个参数就这样 ');
}
function testTwo ( $a , $b ){
echo (' 两个参数的就这样 ');
}
function testThree ($a, $b, $c ) {
echo (' 黑黑,这是三个参数的 ');
}
function test () {
$argNum = func_num_args ();
// 这一段其实可以用 $_arg = func_get_args() 来获得所有的参数,只是要用数组而已,不方便我下面的表达,呵呵
for ( $i = 0 ; $i < $argNum ; $i ++ ) {
$_arg_ { $i } = func_get_arg ( $i );
}
switch ( $argNum ) {
case 1 :
testOne( $_arg_1 );
break ;
case 2 :
testTwo( $_arg_1, $_arg_2 );
break ;
case 3 :
testThree( $_arg_1, $_arg_2, $_arg_3 );
break ;
default :
echo ( ' 这是没有参数的情况 ' );
break ;
}
}
test();
echo ( ' ' );
test( 1 );
echo ( ' ' );
test( 1 , 2 );
echo ( ' ' );
test( 1 , 2 , 3 );
// 这些只是在函数中的运用,其实最主要的还是在类中的运用
//如果这些用到类里面我就不需要担心构造函数是否有几个参数了,不是吗?
class test {
var $a = 0 ;
var $b = 0 ;
function test () {
$argNum = func_num_args ();
$_arg = func_get_args ();
switch ($argNum ) {
case 1 :
$this -> test1( $_arg [ 0 ] );
break ;
case 2 :
$this -> test2( $_arg [ 0 ] , $_arg [ 1 ]);
break ;
default :
$this -> a = 0 ;
$this -> b = 1 ;
break ;
}
}
function test1 ($a) {
$this -> a = $a ;
}
function test2 ($a, $b) {
$this -> a = $a ;
$this -> b = $b ;
}
}
?>
以上所述就是本文的全部内容了,希望大家能够喜欢。
标签:php,伪重载
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python中的集合介绍
2022-09-10 03:49:52
![](https://img.aspxhome.com/file/2023/1/101111_0s.png)
asp xmlhttp下载一句话
2013-06-30 06:47:48
python委派生成器的具体方法
2022-06-14 01:23:39
![](https://img.aspxhome.com/file/2023/8/120988_0s.png)
MySQL无法启动几种常见问题小结
2024-01-18 06:05:32
基于bootstrap写的一点localStorage本地储存
2024-05-10 14:00:12
基于tensorflow for循环 while循环案例
2022-01-26 14:40:34
python中MySQLdb模块用法实例
2024-01-25 01:19:27
Javascript脚本获取form和input内容的方法(两种方法)
2024-04-29 13:18:08
![](https://img.aspxhome.com/file/2023/6/132756_0s.png)
Python3日期与时间戳转换的几种方法详解
2021-03-10 03:57:17
asp form 表单验证函数
2011-04-04 11:10:00
Python实现求最大公约数及判断素数的方法
2021-06-13 02:20:20
Python利用ORM控制MongoDB(MongoEngine)的步骤全纪录
2023-05-08 14:22:05
python进行参数传递的方法
2023-05-21 06:15:32
ubuntu 18.04搭建python环境(pycharm+anaconda)
2023-09-23 20:01:56
![](https://img.aspxhome.com/file/2023/9/62579_0s.png)
Microsoft SQL Server 2012 数据库安装图解教程
2024-01-13 18:20:25
![](https://img.aspxhome.com/file/2023/7/84347_0s.jpg)
Django项目使用CircleCI的方法示例
2022-10-17 11:43:24
MySQL数据库主机127.0.0.1与localhost区别
2024-01-17 17:54:24
Python OpenCV实现基本图形绘制
2023-09-25 12:34:08
![](https://img.aspxhome.com/file/2023/6/133556_0s.jpg)
Python 用户输入和while循环的操作
2023-07-22 22:17:33
Python使用pickle模块储存对象操作示例
2021-05-17 00:29:49