variable scope in php function - php

Here is my script.
I declared few variable outside function. I want to use it in function, would it be available?
<?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;
}
?>

A function has its own scope. You have to provide all variables you want to use in arguments except if they are in the $_SESSION, $_SERVER etc. variables.

Hand it over via parameter:
function lookup($userid, $connection) {
//code here
}
Only Superglobals are availible inside functions. Everything else is handed over via parameters.

You can use outside variable by defining them as global or you can pass them to functions as a parameters.
$str= 'str';
function test()
{
global $str;
echo $str;
}
or
function test($str)
{
echo $str;
}

using the global keyword should do the trick:
$foo = '123';
function bar() {
global $foo;
echo $foo;
}
but the way I see it, you could just pass the variable to that function instead.

Related

Won't read variable in function in another script

Whenever I leave my input field empty, $error['commment'] should be set and echoed, but it won't echo, but if I just say echo "some text";, it echo's it.
The comments function is in my functions.php file and $error[] = array() is given in my text.php file above my comments() function, so I don't understand why it's not working, please help guys.
The last bit of PHP code is in a while loop that has to display all the results of my SQL query.
Code above my HTML in text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
comments();
?>
Code in my functions.php:
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
$filledIn = true;
if (empty($text)) {
$error['comment'] = "No text filled in";
$filledIn = false;
}
}
}
This is the code in my text.php:
<?php
if(isset($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Because $error is not in the scope of the comments() function. So $error['comment'] never gets set.
Ideally you would want to do something like this:
text.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error['comment'] = comments();
functions.php
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
if (empty($text)) {
return "No text filled in";
}
}
return null;
}
text.php
<?php
if(!empty($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Rather than setting the array key "comments" directly I would use a return value from the comments() function to set it. This allows you to avoid having to use global variables.
Edit: I removed the $filledIn variable from comments() because it wasn't being used in the provided code.
#pu4cu
imo, since you dont come across as very advanced, so that you dont have to make many code changes to what you have now which might get you the minimal edits, and easiest for you to understand;
if in your comment function, you just return a response from this function, like a good little function does, then your response will be available when you call the function, when you set that function to a variable.
//functions.php (note this sets error to true to be failsafe, but this depends on how your using it. set the $response to an empty array in the first line instgad, i.e. array(); if you don't want it failsafe.
<?php
function comments()
{
$response = array(
'error' => TRUE,
'filledIn' => FALSE
);
if (isset($_POST['submit']))
{
$text = $_POST['text'];
$response['filledIn'] = TRUE;
if (empty($text))
{
$response['error']['comment'] = "No text filled in";
}
else{
$response['error'] = NULL;
}
}
return $response;
}
//index.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$response = comments();
//text.php
<?php
if($response['error']['comment'])) echo "<p class='error'>".$response['error']['comment']."</p>";
I find your code overly complicated, 3 files, 2 includes, and 1 function, when all you really needed is this:
$error = array();
$error['comment'] = empty($_POST['text']) ? "No text filled in" : $_POST['text'];
echo "<p class='error'>".$error['comment']."</p>";
Your scopes are all mixed up. Your comments() function checks for $_POST, which should be checked before the function is called, and then tries to set a variable within its scope, but you try to access the same variable from outside.
The correct way would be:
text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
if (isset($_POST['submit']) {
comments($_POST);
}
?>
functions.php
function comments($data){
if (isset($data['text'])) {
$text = $data['text'];
if (empty($text)) {
return array('comment' => 'No text filled in');
}
return true;
}
return null;
}
Then you can use the values returned by your function on to act on the result.

How can I access a variable inside another function?

I have two functions that print some values. I need to use the variable $mv in the second function. However, $mv can only be defined in the first function. I have tried all types of PHP global examples and none of them has allowed the $mv variable to be used or visible or accessible in the second function.
function printMobilePrev(&$mobileprevresults) {
if (count($mobileprevresults->getRows()) > 0) {
$mv = $mobileprevRows[0][0];
$mobileprevRows = $mobileprevresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
} else {
print '<p>No results found.</p>';
}
}
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
$mobdiff = ($mobcur - $mv);
$mobpctchg = ($mobdiff / $mobprev) * 100;
$mobilecurrRows = $mobilecurrresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
echo '<p>Previous period (sessions): '.$mv.'..............................';
echo '<p>Current period (sessions): '.$mobilecurrRows[0][0].'..............................';
if ($mobdiff > 0){
echo '<p>Percent increase: '.$mobpctchg.'..............................';
} else {
echo '<p>Percent decrease: '.$mobpctchg.'..............................';
}
} else {
print '<p>No results found.</p>';
}
}
You can use the global scope:
That is what you want to do:
$mv = 0;
function function1()
{
global $mv;
$mv = 'whatever';
//code
}
function function2()
{
global $mv;
// use $mv;
}
You have to predefine that variable OUTSIDE any function, and then you can use Global to get that to any function.
You can pass it by reference. For example
function doSomething(&$mv) {
$mv = 1;
}
function doSomethingElse($mv) {
return $mv;
}
$mv = 0;
doSomething($mv);
echo doSomethingElse($mv); //Output: 1
You could return $mv after your print and save that in a var to pass to the next function:
$printMobilePrev = printMobilePrev();
function printMobilePrev(&$mobileprevresults) {
$mv = $mobileprevRows[0][0];
...
print '<p>No results found.</p>';
return $mv;
...
}
$printMobileCurr = printMobileCurr(&$mobilecurrresults,$mv);
function printMobileCurr(&$mobilecurrresults,$mv) {
......
}
Most likely you have to make a correct use of globals.
declare your $mv variable as global before asigning it a value on your first function
global $mv;
$mv = $mobileprevRows[0][0];
use global at the begining on your second function before using it
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
global $mv;

PHP variables lost their values?

So, I'm trying to build a template-loader system with PHP. Here's what I got so far:
config.php:
<?php
$style_assets_path = "/includes/styles/";
$template = "";
if ($_GET['pageid'] <= 100) {
$template = "/main/main.php";
}
function loadTemplate() {
global $style_assets_path;
global $template;
require_once dirname(__FILE__) . $style_assets_path . "templates" . $template;
}
?>
home.php:
<?php
$page_title = "Homepage";
$menu_selected = "active";
$menu_selected_2 = "";
$menu_selected_3 = "";
$menu_selected_4 = "";
$content_heading = "Featured Content";
$page_contents = "";
$special_id = "home";
require_once dirname(__FILE__) . "/config.php";
if ($_GET['pageid'] !== '1'){
header('Location: /home.php?pageid=1');
exit(0);
}
loadTemplate();
?>
So the variables:
$page_title = "Homepage";
$menu_selected = "active";
$menu_selected_2 = "";
$menu_selected_3 = "";
$menu_selected_4 = "";
$content_heading = "Featured Content";
$page_contents = "";
$special_id = "home";
don't have their values even if declared?
What am I doing wrong?
You are calling require_once inside a function, so only local variables and ones declared global will be available to the required file.
function loadTemplate() {
global $style_assets_path;
global $template;
require_once dirname(__FILE__) . $style_assets_path . "templates" . $template;
}
You would need to declare all these variables global, like so.
function loadTemplate() {
global $style_assets_path,
$template,
$page_title,
$menu_selected,
$menu_selected_2,
$menu_selected_3,
$menu_selected_4,
$content_heading,
$page_contents,
$special_id;
require_once dirname(__FILE__) . $style_assets_path . "templates" . $template;
}
UPDATE:
It's not clear how the files are organized, but it might be necessary to set all the variables with global.
global $page_title = "Homepage";
As said in the comments, this is probably not the best way to make a template engine.
include() and require() work as if you've literally cut/pasted the included text into the location where you called include()/require(). Since you're doing your include() INSIDE a function call, the variables you set are inside that function's scope. When you return from the function, the variables are destroyed as part of the post-function cleanup.
e.g. consider this:
inc.php:
<?php
$foo = 'bar';
test.php:
<?php
function baz() {
include('inc.php');
echo "Inside baz(): $foo\n";
}
baz();
echo "Outside baz(): $foo\n";
You get this as output:
inside baz(): bar
PHP Notice: Undefined variable: foo in /home/marc/test.php on line 9
Outside baz():
Note how the "outside" output produced an undefined variable notice.

PHP variable scoping

I'm having some trouble with variable scoping in PHP. Here's the structure of my code--
<?php
$loader = new ELLoad();
$sessionid = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
global $loader;
$loader->load($file['text']);
global $sessionid;
$sessionid = $loader->getSessionId();
}
if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
global $sessionid;
$extractor->extract($sessionid); //$session id for some reason is still ' ' here
}
The sequence of the requests from the client is always load followed by extract. Can anyone tell me why my $sessionid variable may not be getting updated right?
$sessionid is still '', because It's not change if first condition == false
Improvement of your code:
$loader = new ELLoad();
$sessionid = $loader->getSessionId();
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
$loader->load($file['text']);
// do more stuff
}
else if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
$extractor->extract($sessionid);
// do more stuff
}
Also It's better to use $_GET or $_POST depend on your case, instead of $_REQUEST and finally using else if in separate and repeated conditions.
You don't have to declared global $... unless you're in a function. A block (if, while, ...) have the same scope than the line just before.
I don't know what you want to do, but you have to keep you $sessionid content in a real session, like:
<?php
session_start();
$loader = new ELLoad();
$_SESSION['id'] = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
$loader->load($file['text']);
$_SESSION['id'] = $loader->getSessionId();
}
if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
$extractor->extract($_SESSION['id']); //$session id for some reason is still ' ' here
}

How to get $var outside the function without using global php?

Need small help here. Was reading how bad it is to add global var within function and call it outside but having small issue getting the vars outside. Global helped but I want to be safe also since I am handling some files here
my loop is this
<?php
require_once('functions.php');
?>
<?php
foreach( $files as $key=> $file ){
global $download_link;
get_file_info($key,$file);
?>
<span><?php echo $file->name ?></span>
<?php } ?>
PART of my function.php / is about 150 lines long but this is main snipp
function get_file_info($key,$file){
global $download_link;
$access = explode(",",$file->access);
$permission = in_array(1,$access);
if($permission){
$download_link = 'ok to download';
}else{
$download_link = 'canot download';
}
}
beside the link var I also have few others like date , counter etc but they are all bound by some condition.
I tried to do
return $link; at the end of the function instead using global but getting undefined variable error;
SO base question here is , how to get the download_link var outside the function without using global ?
You can do this a lot easier by modifying your File class
class File {
# ...
function get_url() {
return in_array(1, explode(',', $this->access))
? $this->url # return the file's url
: "/path/to/subscribe" # return a default path for non-access
;
}
}
Your HTML would use it as follows
<?php
foreach ($files as $file) {
echo 'Download this '.$file->name.'';
}
Since you just use get_file_info to set $download_link, why not just return $permission and define $download_link outside the function?
<?php
function get_file_info($key,$file){
$access = explode(",",$file->access);
$permission = in_array(1,$access);
return $permission;
}
foreach( $files as $key=> $file ){
$download_link = 'canot download';
if(get_file_info($key,$file)) {
download_link = 'ok to download';
}
echo '<span>'. $file->name . '</span>';
}
?>
You may change your loop like this:
<?php
require_once('functions.php');
?>
<?php
foreach( $files as $key=> $file ){
$download_link = get_file_info($key,$file);
?>
<span><?php echo $file->name ?></span>
<?php } ?>
And your function code:
function get_file_info($key,$file){
$access = explode(",",$file->access);
$permission = in_array(1,$access);
if($permission){
return 'ok to download';
}
else {
return 'canot download';
}
}

Categories