简体   繁体   English

可以在php中实例化一个函数吗?

[英]Is it possible to instantiate a function in php?

I am looking a PHP script example that contains the mysqli extension. 我正在寻找一个包含mysqli扩展的PHP脚本示例。 The code in question is as follows: 有问题的代码如下:

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");

I'm confused as to wether this is a function or a class instance. 我很困惑这是一个函数或类实例。 If it is a function, is it possible to instantiate a function? 如果它是一个函数,是否可以实例化一个函数?

What confuses you is the constructor. 令你困惑的是构造函数。

This is a special public function inside a class which get's called straight after an instance gets created. 这是一个类中的特殊公共函数,它在创建实例后直接调用。

mysqli in your case is a class, which has a constructor like this: 在你的情况下mysqli是一个类,它有一个像这样的构造函数:

public function __construct($server, $user, $password, $dbname) {
 // do something
}

See: 看到:

http://php.net/manual/en/mysqli.construct.php http://php.net/manual/en/mysqli.construct.php

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

Geekfact: Geekfact:

You can somehow get an "instance" of a function by using closures. 你可以通过使用闭包以某种方式获得函数的“实例”。 These arent real instances, just callables . 这些不是真实的例子,只是callables

function createInstance() {
    return function($a, $b) {
        return $a + $b;
    };
}

$myIndependendFunction = createInstance();

echo $myIndependendFunction(3, 2); // prints 5

You declare functions and use it , you declare objects (mysqli object in this case) and you instantiate it . 你声明函数使用它 ,你声明对象 (在这种情况下是mysqli对象)并实例化它

You can read the manual. 你可以阅读手册。 http://www.php.net/manual/en/language.oop5.basic.php http://www.php.net/manual/en/language.oop5.basic.php

If you want to contain your instantiation logic in one place you could wrap your current code within a function and return the ready to use mysqli class? 如果要在一个地方包含实例化逻辑,可以将当前代码包装在一个函数中并返回准备使用的mysqli类?

Example: 例:

<?php

function getMysqliConnection(){
    return new mysqli("myServer", "myUser", "myPassword", "Northwind");    
}

$conn = getMysqliConnection();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM