drgzmmy6379 2014-05-03 01:15
浏览 30
已采纳

PHP:使用我班级中外部文件的变量

I have a settings.php file that looks something like this:

$user="adam";
$pass="something";

then I have a class called funcs.php, in which I have a require "../settings.php" on top, but I don't know how to get the scope of "$user" into my methods...

I'm sure this is an easy fix, but I've been googling in circles for a while with no luck.

My class looks something like this:

<?php
require_once __DIR__."/../settings.php";

class Funcs
{

    public function something()
    {
        // do stuff
return $user;

    }
}
  • 写回答

2条回答 默认 最新

  • duanlan3598 2014-05-03 01:19
    关注

    you can use the return construct inside file which can return anything, but if you want to return multiple values, it's best to use an array.

    settings.php

    return array(
      'user' => 'adam',
      'pass' => 'something'
    );
    

    file.php

    $settings = require __DIR__.'settings.php';
    
    echo $settings['user']; // adam
    

    To pass everything returned from the file into a class:

    class MyClass {
      public function __construct(array $array) {
        foreach($array as $key => $value) {
          $this->{$key} = $value;
        }
      }
    }
    
    $class = new MyClass(require __DIR__ . '/settings.php');
    var_dump($class);
    /*
     class MyClass#1 (2) {
      public $user =>
      string(4) "adam"
      public $pass =>
      string(9) "something"
    }
    */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改