views:

54

answers:

3

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 regarding this, plus google returned no real results. Does anyone have any idea ?

+2  A: 

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.

Mike B
I failed to mention that I do use require_once.
Adrian A.
Well, nothing you're doing is wrong in the eyes of PHP. Without the rest of your code it's impossible to give you a solution.
Mike B
A: 

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
}
John Conde
This is a wordpress install and I'm working on a plugin, so I'd need to hack all the levels in order to pass the variable ( I presume that's you're idea )
Adrian A.
+1  A: 

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.

Ondrej Slinták