繁体   English   中英

PHP函数中的变量范围

[英]variable scope in php function

这是我的剧本。 我声明了几个外部函数变量。 我想在功能中使用它,它将可用吗?

<?php

session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('follow.php');

require_once('config.php');

if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$userid = $content->{'id'};
$temp = "1";
$tweets1 = $connection->get("https://api.twitter.com/1.1/statuses/retweets_of_me.json?count=200");
$tweets3 = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?trim_user=true&include_rts=true");

$tweets4 = $connection->get("https://api.twitter.com/1.1/statuses/home_timeline.json?include_rts=true&trim_use=true");

foreach ($tweets1 as $item)
{
$text = $item->text;
$follow_count = getfollow($m[1]);
echo "followe count is $follow_count <br>";
lookup($item->user->id_str);

}

function lookup($userid)
{
//echo "userid : $userid temp : $temp";
$tweets5 = $connection->get("https://api.twitter.com/1.1/users/lookup.json?user_id='.$userid.' ");

$CONNECTION IS not availabl here? WHY?

foreach ($tweets5 as $item)
{
$text = $item->name;

}
return;
}

?>

函数有其自己的范围。 您必须提供要在参数中使用的所有变量,除非它们在$ _SESSION,$ _ SERVER等变量中。

通过参数移交:

function lookup($userid, $connection) {
    //code here
}

函数内部仅提供Superglobals。 其他所有内容都通过参数移交。

您可以通过将外部变量定义为全局变量来使用外部变量,也可以将它们作为参数传递给函数。

$str= 'str';

function test()
{
    global $str;
    echo $str;
}

要么

function test($str)
{
    echo $str;
}

使用global关键字应该可以解决问题:

$foo = '123';

function bar() {
    global $foo;
    echo $foo;
}

但是从我的角度来看,您可以只将变量传递给该函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM