include_once 是 PHP 中用于在当前脚本中包含指定文件的功能,如果该文件已经被包含过,则不会再重复包含。这有助于避免函数定义或类定义等代码片段的重复执行,从而提高代码的复用性。
要提高代码复用性,可以遵循以下几个建议:
functions.php),将常用的函数和类放入其中。这样,在其他项目中需要使用这些函数和类时,只需引入这个公共库文件即可。// functions.php function sayHello($name) { echo "Hello, $name!"; } class Greeter { public function greet($name) { echo "Hello, $name!"; } } include_once 或 require_once 语句引入公共库文件。// index.php include_once 'functions.php'; sayHello('John'); $greeter = new Greeter(); $greeter->greet('John'); // subfolder/another_script.php include_once '../functions.php'; sayHello('Jane'); $greeter = new Greeter(); $greeter->greet('Jane'); 通过以上方法,你可以利用 include_once 提高代码的复用性,减少重复代码,使项目结构更加清晰。