简体   繁体   中英

Is it possible to instantiate a function in php?

I am looking a PHP script example that contains the mysqli extension. 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:

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

See:

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

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

Geekfact:

You can somehow get an "instance" of a function by using closures. These arent real instances, just 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 .

You can read the manual. 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?

Example:

<?php

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

$conn = getMysqliConnection();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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