我在一个外部文件中有两个变量
function.php
$bottomID = get_post_meta($post->ID, "bottom", true);
$xstring = "This is a string";
现在如果我从index。php
回显它们echo $bottomID;
echo $xstring;
我只得到$xstring
的值,而没有得到$bottomID
的值
我知道$bottomID
工作,因为如果我在index.php
文件中有它,它会回显一个值。
我想不出是什么问题
任何想法?
如果你在function.php
中设置了一个变量,它是在全局作用域中,变量将在index.php
中可见,因为它们是在相同的作用域中加载的,但它不是对所有模板都可用。大多数模板都是由函数加载的,在PHP中,函数内部使用的任何变量默认情况下都局限于局部函数作用域,所以你必须显式地将变量定义为全局变量。
在您的示例中,设置了变量,值为false
(在index.php
中使用:var_dump( isset( $bottomID ) );
进行测试),这是因为您在get_post_meta()
函数中使用了尚未存在的global $post
作为参数,因此该函数的返回值为false
。
我会在functions.php
中编写一个函数,并在index.php
中调用它。
function get_id_xstring()
{
global $post;
$return = array(
'id' => get_post_meta( $post->ID, 'bottom', true ),
'xstring' => 'This is a string';
);
return $return;
}
在index.php
:
$my_vars = get_id_xstring();
echo $my_vars['id']; // bottomID
echo $my_vars['xstring'];