2010-05-31 79 views
1

我想要包含一个文件,以便在任何PHP类的方法/函数中都可以访问。该文件只包含一个base-64编码变量。我该怎么做呢?如何在课堂中包含文件?

谢谢。

+0

“该文件只包含一个base-64编码变量” - 作为PHP代码,比如' VolkerK 2010-05-31 10:12:37

+0

是的,那是正确的 – 404Error 2010-05-31 10:13:05

+0

您是否可以控制此文件,即a)它是否值得信赖b)您可以更改格式吗? – VolkerK 2010-05-31 10:17:38

回答

3

对于这种情况,最好使用常量。

define('MY_BASE64_VAR', base64_encode('foo')); 

它将随处可用并且是不可变的。

require "constant.php"; 
class Bar { 
    function showVariable() {echo MY_BASE64_VAR;} 
} 

当然,您仍然需要在将文件用于课程之前将其包含在其中。

2
<?php include("common.php"); ?> 

检查here

0

如果你想确保它包含在每类中,请务必将其包含在每一个类,但使用include_once为efficency

<?php include_once("common.php"); ?> 
0

如果你只是保存base64编码数据,没有任何该文件中的其他php代码可以简单地读取其内容,解码数据并将其分配给对象的属性。

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(); 

打印x=mary had a little lamb

(您可能要脱钩,更多一点......但它只是一个例子。)