Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a file in a class in PHP

Is it possible to include a file with PHP variables inside a class? And what would be the best way so I can access the data inside the whole class?

I have been googling this for a while, but none of the examples worked.

like image 236
Jerodev Avatar asked Aug 14 '11 10:08

Jerodev


People also ask

What are the ways to include file in PHP?

PHP Include Files. The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.

HOW include class from another file in PHP?

Use include("class. classname. php");

How are classes loaded in PHP?

PHP load classes are used for declaring its object etc. in object oriented applications. PHP parser loads it automatically, if it is registered with spl_autoload_register() function. PHP parser gets the least chance to load class/interface before emitting an error.


2 Answers

The best way is to load them, not to include them via an external file.

For example:

// config.php
$variableSet = array();
$variableSet['setting'] = 'value';
$variableSet['setting2'] = 'value2';

// Load config.php ...
include('config.php');
$myClass = new PHPClass($variableSet);

// In a class you can make a constructor
function __construct($variables){ // <- As this is autoloading, see http://php.net/__construct
    $this->vars = $variables;
}
// And you can access them in the class via $this->vars array
like image 63
Mihai Iorga Avatar answered Sep 27 '22 19:09

Mihai Iorga


Actually, you should append data to the variable.

<?php
    /*
        file.php

        $hello = array(
            'world'
        )
    */

    class SomeClass {
        var bla = array();
        function getData() {
            include('file.php');
            $this->bla = $hello;
        }

        function bye() {
            echo $this->bla[0]; // Will print 'world'
        }
    }
?>
like image 41
Ernestas Stankevičius Avatar answered Sep 27 '22 18:09

Ernestas Stankevičius