dongzhazhuo0572 2016-10-23 20:52
浏览 93
已采纳

php从包含文件中访问构造函数中的变量

I have a class where I want to use an API, and I've got the api keys in a separate file in another directory.

The api key file is literally as simple as this:

$id = 'xxxxxxx';
$key = 'xxxxxxx';

This doesn't work:

include '/path/to/file-with-api-keys.php';

class MyApiClass {
    public function __construct($id, $token) {
        $this->client = new Client($id, $token);
    }
}

The code where I instantiate the class is in another php file I'm using to test, and it's extremely simple, just includes the class and then instantiates it:

include '/path/to/MyClass.php';

$result = new MyClass();
$result->myMethod();

echo $result;

The error I get is basically saying the 2 variables are null.

TWO QUESTIONS:

1) How can I access the value of the variables in my constructor? I've read elsewhere that using an include file directly in the method is bad practice, and also that using a global variable would be bad practice as well.

2) Somewhat related question, these files where I'm storing the api keys are in the same directory with my database connection details, but the directory is not outside the root. In this directory I have an .htaccess file with "Deny From All". Is this sufficient from a security standpoint, or should I do something else?

ok 3 questions...

3) Should I even bother keeping the api keys in separate files within this directory or just embed them into my class?

Hoping someone can give me best practices here. Thanks!

  • 写回答

1条回答 默认 最新

  • duanfaxin7014 2016-10-23 21:16
    关注
    1. The constructor won't read the variables from file-with-api-keys.php automagically. You must specify them like this when instantiating the class: $result = new MyClass($id, $key);

    2. The best practice is to store all your PHP scripts outside the webroot directory except index.php (aka front controller).

    3. Yes, you should bother :) All configuration, API keys etc. should be stored in separate files, outside your classes code. You shouldn't mix these two things. If you're going to use some version control system like Git, then you're going to commit your classes code without any configuration details. The latter will be in your .gitignore file. If you ever work in a team of programmers, then every one of them is going to have his separate configuration files.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载