【问题标题】:Calling a single function from another file without including the whole file in php从另一个文件调用单个函数而不在 php 中包含整个文件
【发布时间】:2014-02-02 03:40:23
【问题描述】:

是否可以只调用另一个文件中的特定函数而不包括整个文件??? 文件中可能还有其他函数,不需要渲染其他函数。

【问题讨论】:

  • 不包含文件怎么调用里面的函数。
  • 您可以将函数复制到当前文件中。不然不行,php没有拿到文件怎么知道函数呢?
  • 也许将文件分解成更模块化的组件,例如每个文件 1 个类。

标签: php function include


【解决方案1】:

包含一个页面,假设函数是 GetPage,变量是 ID

<?php
require('page.php');

$id = ($_GET['id']);

if($id != '') {
  getpage($id);
}
?>

现在当你制作函数时

<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>

【讨论】:

    【解决方案2】:

    在 PHP 中,不能只获取文件的一小部分。

    也许这是一种只使用文件的一小部分的能力:

    我有一个名为“实用程序”的课程。这是我在我的项目中使用的。

    在我的 index.php 中

    include("class.utilities.php")
    $utilities = new utilities();
    

    文件class.utilities.php

    class utilities {
        function __construct() {
    
        }
        public function thisIsTheFunction($a,$b)
        {
            $c = $a + $b;
            return $c;
        }
    }
    

    然后我就可以使用该功能了

    echo $utilities->thisIsTheFunction(3,4);
    

    【讨论】:

      【解决方案3】:

      简短的回答是:不,你不能。

      长答案是:是的,如果您使用 OOP。

      将您的函数拆分为不同的文件。假设您正在与英雄一起制作游戏:

      Walk.php

      function walk($distance,speed){
         //walk code
      }
      

      Die.php

      function die(){
          //game over
      }
      

      英雄.php

      include 'Walk.php';
      include 'Die.php';
      
      class Hero(){
          //hero that can walk & can die
      }
      

      你可能有其他函数,如makeWorld(),hero.php 不需要,所以你不需要包含它。这个问题之前已经问过几次了:here & here。

      之前列出的一种可能的方法是通过autoloading,这基本上可以让您不必在每个文件的顶部编写一长串包含的内容。

      【讨论】:

      • 您可能希望将您的答案与 OP 提出的实际问题联系起来。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      相关资源
      最近更新 更多