【问题标题】:Access variable in defined in a function outside of that function在该函数之外的函数中定义的访问变量
【发布时间】:2014-01-25 01:48:01
【问题描述】:

首先:我知道以前有人问过这个问题,但我查看了很多问题/答案,但我无法弄清楚如何让它们中的任何一个起作用。所以,很抱歉。

所以基本上我在 Wordpress 中编写了一些函数/简码,这意味着我可以使用简码将 Vine 视频发布到 Wordpress 博客:

function embedVine($atts) {

    extract(shortcode_atts(array(
        "id" => ''
    ), $atts));

    $vine_id = $id;

   // I'm then doing a whole load of stuff involving $vine_id, including using it as a parameter to pass to different functions I've written that are separate to this function.
  // I should also mention that $vine_id is the id on the end of a Vine URL.
} add_shortcode("vine", "embedVine");

然后用户可以在 Wordpress 编辑器中使用 [vine id="..."] 短代码。

然后我编写了一个函数,但我不想在上面的函数内部执行它,否则每次函数/短代码运行时它都会运行,这不好。相反,我需要在函数之外执行它,但仍然使用 $vine_id 作为它的参数。但是,由于$vine_id 是在上面的函数内部定义的,所以我无法在函数外部访问它。

这是第二个功能:

function vineThumb($id) {
    $vine = file_get_contents("http://vine.co/v/{$id}");
    return $vine;
    // of course, it's a lot more complicated than this but for the sake of this, it works.
} vineThumb($vine_id);

执行该函数将返回http://vine.co/v/{$vine_id}。如何使 $vine_id 函数在短代码函数(第一个函数)之外可访问?

希望我已经解释得足够清楚了,我不是你可能知道的 PHP 程序员,但我知道的足够多。这种类型让我很难过。感谢您的帮助:)

【问题讨论】:

    标签: php wordpress scope shortcode


    【解决方案1】:

    我不知道这两个函数是否位于同一个文件中,但试试这个。 http://www.php.net/manual/en/language.variables.scope.php

    $vine_id = null; //Define it outside the function
    
    function embedVine($atts) {
    
        global $vine_id; //Refers to $vine_id outside the function
    
        extract(shortcode_atts(array(
            "id" => ''
        ), $atts));
    
        $vine_id = $id; //$vine_id now has the value of $id when embedVine exits
    } add_shortcode("vine", "embedVine");
    

    【讨论】:

    • 不幸的是,这似乎不起作用:(尽管感谢您的帮助:)我认为我需要做的是能够以某种方式返回 $vine_id 作为可访问的函数的结果我的次要功能。不知道该怎么做:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2014-04-09
    • 1970-01-01
    • 2011-06-23
    • 2014-02-10
    • 2019-09-15
    相关资源
    最近更新 更多