Hey,
I want to include a file to be accessible to any method/function in a PHP class. The file just contains a base-64 encoded variable. How do I do this?
Thanks.
Hey,
I want to include a file to be accessible to any method/function in a PHP class. The file just contains a base-64 encoded variable. How do I do this?
Thanks.
For this situation, you'd better use a constant.
define('MY_BASE64_VAR', base64_encode('foo'));
It will be available everywhere and immutable.
require "constant.php";
class Bar {
function showVariable() {echo MY_BASE64_VAR;}
}
Of course, you will still need to include the file where it is defined prior to using it in you classes.
if you want to make sure that it is included in every class, make sure you include it in every class but use the include_once for efficency
<?php include_once("common.php"); ?>
If you just save the base64 encoded data, without any additional php code in that file you can simply read its contents, decode the data and assign it to a property of the object.
class Foo {
protected $x;
public function setSource($path) {
// todo: add as much validating/sanitizing code as needed
$c = file_get_contents($path);
$this->x = base64_decode($c);
}
public function bar() {
echo 'x=', $this->x;
}
}
// this will create/overwrite the file test.stackoverflow.txt, which isn't removed at the end of the script.
file_put_contents('test.stackoverflow.txt', base64_encode('mary had a little lamb'));
$foo = new Foo;
$foo->setSource('test.stackoverflow.txt');
$foo->bar();
prints x=mary had a little lamb.
(You might want to decouple that a bit more ...but it's only an example.)