php中不同方法中同名方法的处理

近日查看codeigniter源码,发现其helper类可以自定义方法,从而对系统helper方法进行扩展或重写。

CI  herper类介绍http://codeigniter.org.cn/user_guide/general/helpers.html

对于类可以继承实现方法的重写或扩展,对于方法可以吗?于是做了一下尝试


创建两个引用文件,里面有一个同名方法。

include1.php

function testfun() {
	echo 'this is function 1';
}

include2.php

function testfun() {
	echo 'this is function 2';
}

调用脚本test.php
include './include2.php';
include './include1.php';
testfun ();

执行test.php时候系统报错:Fatal error: Cannot redeclare testfun() 

看来在引用多个脚本文件时候不能包含同名方法。否则在调用时候,php分不清执行哪个定义方法。

如果引用脚本都是类就不存在此问题,因为调用方法需要实例化类。

后来查看ci的实现原理,每个方法最外层嵌套 function_exists函数

这样两文件变为

include1.php

if (!function_exists ( 'testfun' )) {
	function testfun() {
		echo 'this is function 1';
	}
}

include2.php

if (! function_exists ( 'testfun' )) {
	function testfun() {
		echo 'this is function 2';
	}
}
这样再调用test.php时候,会输出  this is function 1.如此实现了方法的重写。

但是需要注意几点

1.注意引用的顺序,先引用的为准

2.引用过多文件时,不会出现方法覆盖,可能达不到想要的效果

   如果需要这种方法重写的话,需要清楚所引用的文件,ci中用框架规范了使用方法。



原文地址:https://www.cnblogs.com/y0umer/p/3838875.html