0

我正在开发一个自定义 wordpress 模板。我有一些用于布局的页面模板。我分别在页面模板的顶部和底部调用 get_header() 和 get_footer()。

现在的问题是。我在 header.php 文件中使用了两个或三个 require_once() 来包含 php 类文件。在其中一个包含的文件中,我为包含的类文件创建了一个对象。但是当我在我的页面文件中调用这些对象时(--我使用 get_header()--)它说未定义的变量。

这是我的 wordpress header.php

// THIS IS MY header.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if(session_id() == '')
    session_start(); 

date_default_timezone_set('Asia/Dubai');

require_once('risk-profiler/configuration.php'); // Config file
require_once('risk-profiler/dal.php'); // One class files
require_once('risk-profiler/bl.php'); // another class file
require_once('risk-profiler/form_handler.php'); // Were Objects for the classes are created
?>

form_handler.php

if (!isset($data))
    $data = new DataAccessLayer(sql_server, sql_user, sql_password, sql_database);
if (!isset($bl))
    $bl = new businessLogic;

$data 是我的数据库类对象,$bl 是另一个类的对象。

现在这是我调用get_header() risk_profile_questionnaire.php的地方,我在这个文件(表单)中包含了两个表单(risk-profile-select-profiling-country.php 和 another.php)是我调用该对象的地方,它不是无障碍。

risk_profile_questionnaire.php

<div class="form-group">
            <label for="" class="col-md-4 control-label">Country : </label>
            <div class="col-sm-8">
                <select class="form-control input-lg" name="version_details">
                    <?php
                        $version_details = $data->get_version_list();
                        while ($row = mysqli_fetch_array($version_details)) {
                            echo"<option value='" . $row['country_code'] . "|" . $row['version'] . "'>" . $row['country_name'] . "</option>";
                        }
                    ?>
                </select>
            </div>
        </div>

任何人都可以帮我解释为什么我的对象当时无法访问。

4

1 回答 1

1

我现在无法测试,但我的猜测是这是因为变量范围。

如果要在 PHP 中的函数内使用全局变量,则需要在函数开头将其声明为全局变量。

由于您从函数“get_header”中包含 header.php(以及 header.php 中包含的其余文件),因此变量默认限制在“get_header”函数的范围内。

尝试在 header.php 文件的开头声明需要使用的全局变量,例如:

global $data;

PHP 中的变量范围:http: //php.net/manual/en/language.variables.scope.php

于 2018-05-02T10:04:44.383 回答