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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?