Mr. Bug Mr. Bug - 4 months ago 7
PHP Question

Include file content into property?

I've a file called

helper.php
, in this file I've a list of functions (without class).

Now I need to include the content of helper file, into a property. For do this I've create a loader, this is an example:

class Loader
{
function include($helpName)
{
return include $helpName;
}
}


this Loader is used by my class like so:

class Foo
{
function __construct()
{
$this->load = new Loader();
$this->email = $this->load->include('helper.php');
$this->email->send();
}
}


unfortunately I get this error:


Fatal error: Call to a member function validate_email() on integer


if I print:
var_dump($this->email);
I'll get:
int(1)
.

What am I doing wrong?

Answer

Unless you're specifically returning at the end of your class, it doesn't work that way. From the docs:

Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1.

I'd look into autoloading classes, or you can also create a class, and return that from your include.php.

public class Email
{
    public function send()
    {
        echo 'Sending Email';
    }
}

return new Email();

An example with autoloading:

//Create Email.php
public class Email
{
    public function send()
    {
        echo 'Sending Email';
    }
}

//Main file, set a register, so when it doesn't find a class, it will load from a file, and auto register it.
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});


class Foo
{
    function __construct()
    {
         $this->load = new Loader();
         //If Email class doesn't exist, it will load it from 'Email.php', and then initialize it.
         $this->email = new Email();
         $this->email->send();
    }
}