Php 如何在类中包含文件?
我想包括一个PHP类中任何方法/函数都可以访问的文件。该文件只包含一个base-64编码的变量。我该怎么做 谢谢。Php 如何在类中包含文件?,php,Php,我想包括一个PHP类中任何方法/函数都可以访问的文件。该文件只包含一个base-64编码的变量。我该怎么做 谢谢。 <?php include("common.php"); ?> 检查。 检查。对于这种情况,最好使用常数 define('MY_BASE64_VAR', base64_encode('foo')); 它将无处不在,一成不变 require "constant.php"; class Bar { function showVariable() {echo
<?php include("common.php"); ?>
检查。
检查。对于这种情况,最好使用常数
define('MY_BASE64_VAR', base64_encode('foo'));
它将无处不在,一成不变
require "constant.php";
class Bar {
function showVariable() {echo MY_BASE64_VAR;}
}
当然,在类中使用该文件之前,仍然需要将其包含在定义该文件的位置 对于这种情况,最好使用常数
define('MY_BASE64_VAR', base64_encode('foo'));
它将无处不在,一成不变
require "constant.php";
class Bar {
function showVariable() {echo MY_BASE64_VAR;}
}
当然,在类中使用该文件之前,仍然需要将其包含在定义该文件的位置 如果您想确保它包含在每个类中,请确保您在每个类中都包含它,但为了提高效率,请使用include_一次
<?php include_once("common.php"); ?>
如果您想确保它包含在每个类中,请确保在每个类中都包含它,但为了提高效率,请使用一次“包含”
<?php include_once("common.php"); ?>
如果只保存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();
printsx=玛丽有一只小羊羔
(您可能想将其解耦一点……但这只是一个示例。)如果您只保存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();
printsx=玛丽有一只小羊羔
(您可能想将其解耦一点……但这只是一个示例。)“该文件仅包含一个base-64编码变量”-如php代码
,您是否可以控制该文件,即a)它是否可靠b)您可以更改格式吗?“该文件仅包含一个base-64编码变量”-像这样的php代码,你能控制这个文件吗,即a)它可靠吗b)你能改变格式吗?