开发者

Loading a class into a function?

开发者 https://www.devze.com 2022-12-25 04:57 出处:网络
I`m currently working on a script, and I have the following situation. function somnicefunction() { require \'someexternalclass.php\';

I`m currently working on a script, and I have the following situation.

function somnicefunction()
{
    require 'someexternalclass.php';
    $somevar = new SomeExternalClass();
}

For some reason, the above breaks the function. I'm not sure why, I haven't seen much documentation in php.net regard开发者_如何学Pythoning this, plus google returned no real results. Does anyone have any idea ?


If you call the function more than once, you may encounter an error by trying to include the same file.

Try using require_once() instead. Other than that, there is nothing inherently 'illegal' about your example.


Your code is absolutely valid. I tested it on localhost and it works just fine. I used following piece of code:

function.php

function loadClass()
{
    include_once "include.php";
    new SomeExternalClass();
}

loadClass();

include.php

class SomeExternalClass {
    public function __construct( ) {
        echo "loads...";
    }
}

Are you sure you don't have any typo there? If you aren't getting any error, it might indicate that you haven't used the function anywhere.


Try declaring the object first and then pass it as a parameter to the function:

require 'someexternalclass.php';
$somevar = new SomeExternalClass();
function somnicefunction(SomeExternalClass $somevar)
{
    // Do function stuff
}
0

精彩评论

暂无评论...
验证码 换一张
取 消