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 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行