Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中声明函数?_Php_Function - Fatal编程技术网

如何在PHP中声明函数?

如何在PHP中声明函数?,php,function,Php,Function,我只想声明函数,而不声明实现。实现必须在另一个文件中 这是可能的吗?如果是的话,这其中是否有一些棘手的问题? 这样做是否常见?我很好奇,因为我来自C++。 例如: -----------------declarations.php----------- -----------------implementations.php----------- 我认为您想要的是一个接口,尽管它必须在类中实现 由于PHP是一种脚本语言,您仍然需要使用include直接引用实现。没有链接阶段,如C++。 <

我只想
声明
函数,而不声明实现。实现必须在另一个文件中

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

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


-----------------implementations.php-----------


我认为您想要的是一个接口,尽管它必须在类中实现


由于PHP是一种脚本语言,您仍然需要使用
include
直接引用实现。没有链接阶段,如C++。

< P>不,PHP没有等同于头文件,在这里声明全局函数并在某个地方实现。

正如Daniel所写,有一些类似的东西,即接口,但它们的目的是描述所有实现类都必须遵循的接口,而不是指示“函数占位符”


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

您能使用面向对象编程解决此问题吗?带有多个抽象方法的抽象类将做得很好

// 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
    }
}

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

使用
required_once
,你的方法是正确的,但可能不是最佳的。你不能在函数已经声明之后重新声明它,所以他做上述事情的方法都不会起作用。如下所述,虽然切换到OO可能会获得相同的结果。没有与a.h等价的php:(您不一定需要抽象类,接口只满足于标题。
<?php 
include (declarations.php);

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

function second($country)
{
 // here is the other implementation
}
?>
// 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
    }
}