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.
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.
Use include("class. classname. 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.
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
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'
}
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With