douren7179 2015-06-11 13:24
浏览 77

如何在类中包含变量脚本? 未定义的变量

got a script which has string variables that represent data fields like they are in the database. because this project is a complete mess this is a stage in cleaning it up and not having to rewrite the field name in numerous locations.

so one script 'DataKeys.php' will have variables set to field names.

//results from query1
$keyField1  = 'field1';
$keyField2 = 'field2';

these two vars above is only a snippet of a much longer list.

I want to access this file and use these vars when I am formatting the data to be more friendly for the front end. this script is being accessed in a class however the fields, $keyField1, defined in the script is not being found in the class. I did have the actual string there but I think single access point would be best so when I make future changes I don't need search the whole project.

class DataFormatter {
    //put your code here
    public function __construct() {
        $documentRoot = filter_input(INPUT_SERVER, "DOCUMENT_ROOT");
        include ($documentRoot . '/database/values/DataKeys.php');
    }

    public function cleanData($data){
        if (is_null($data) || empty($data)) 
        {
            return;
        }

        foreach($data as $row){
            $field1Value = $row[$keyField1];
            unset($row[$keyField1]);
        }
    }
}

I also tried moving the include outside the class definition.

$documentRoot = filter_input(INPUT_SERVER, "DOCUMENT_ROOT");
include ($documentRoot . '/database/values/DataKeys.php');

The error that is being reported is :

Undefined variable: keyField1

SOULTION Maybe not the optimal way but I took the include statement and placed it inside the function. The code above is just a demo of what I was trying to achieve not the actual code I am using.

  • 写回答

2条回答 默认 最新

  • dqspy04266 2015-06-11 13:29
    关注

    the 2 variables are available just after the "include". you can for example, put the 2 values in properties of the object

    include ...;
    $this->keyField1 = $keyField1;
    $this->keyField2 = $keyField2;
    
    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?