2013-04-18 60 views
0

我只想declare函数没有的实现。这些实现必须位于另一个文件中。如何在PHP中声明函数?

这是可能的,如果是这样,那里有一些棘手的问题吗? 这是否是常见做法?我很好奇,因为我来自C++。

实施例:

----------------- declarations.php -----------

<?php 
function first($name, $age); 
function second($country); 
?> 

- --------------- implements.php -----------

<?php 
include (declarations.php); 

function first($name, $age) 
{ 
// here is the implementation 
} 

function second($country) 
{ 
// here is the other implementation 
} 
?> 
+0

改为使用'required_once',而且你所做的方式是正确的,但可能不是最佳的。 –

+0

你已经声明了一个函数后就不能重新声明它,所以没有办法做到以上不行。如下所述,尽管交换到OO可能会达到相同的结果。有没有php equivilent的.h :( – Dave

回答

5

我想你想要的是一个接口,虽然它必须实现在一个班级。

http://php.net/manual/en/language.oop5.interfaces.php

由于PHP是一种脚本语言,你仍然必须有一个直接引用与include实施。没有像C++这样的链接阶段。

+0

谢谢,我要试试接口 –

1

不,PHP没有相当于头文件的地方,你声明了一个全局函数并在某处执行它。正如丹尼尔所写,有类似的东西,即接口,但其目的是描述所有实现类必须遵守的接口,而不是指示“函数占位符”。

此外,从版本5.4开始,PHP不支持函数或方法重载,因此即使使用不同的参数,同一函数或方法也不能多次声明。

1

你可以使用面向对象的编程来解决这个问题吗?具有几种抽象方法的抽象类会做得很好。

// File: MyClass.php 
abstract class AbstractClass { 

    abstract public function first($arg); 
    abstract public function second($arg, $arg2); 

} 

// File: core.php 
require_once('MyClass.php'); 

class MyClass extends AbstractClass { 

    public function first($arg) { 
     // implementation goes here 
    } 

    public function second($arg, $arg2) { 
     // implementation goes here 
    } 
} 
+0

你不一定需要一个抽象类,一个接口只能用于标题。 –

1

PHP和C++与这一点不同。 无需做出声明并单独实现您的功能。 您必须同时执行此操作(在同一文件中声明和实现),然后在脚本中包含(include()或require_once())函数。