Include a file in a class in PHP

28,409

Solution 1

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

Solution 2

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'
        }
    }
?>

Solution 3

From a performance point of view, it would be better if you will use a .ini file to store your settings.

[db]
dns      = 'mysql:host=localhost.....'
user     = 'username'
password = 'password'

[my-other-settings]
key1 = value1
key2 = 'some other value'

And then in your class you can do something like this:

class myClass {
    private static $_settings = false;

    // This function will return a setting's value if setting exists,
    // otherwise default value also this function will load your
    // configuration file only once, when you try to get first value.
    public static function get($section, $key, $default = null) {
        if (self::$_settings === false) {
            self::$_settings = parse_ini_file('myconfig.ini', true);
        }
        foreach (self::$_settings[$group] as $_key => $_value) {
            if ($_key == $Key)
                return $_value;
        }
        return $default;
    }

    public function foo() {
        $dns = self::get('db', 'dns'); // Returns DNS setting from db
                                       // section of your configuration file
    }
}
Share:
28,409
Jerodev
Author by

Jerodev

I'm a certified Laravel developer who likes to work with Laravel, TailwindCSS and Vue.js. Occasionally I try some things in Golang. In my spare time, I work on multiple projects including but not limited to TableTopFinder &amp; Breakout.

Updated on July 19, 2022

Comments

  • Jerodev
    Jerodev almost 2 years

    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.