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';
}
}
Related
I created a function in my function.php to retrieve some variables. To be clear, at the beginning of my project, I put those variables in my template, and they worked fine, but I want to write better code, so I want to rewrite my code, put in the function.php file and then call the function to print the value in my template.
So now my approach is different, here's my example:
function programpagedata() {
global $post;
$url = $_SERVER['REQUEST_URI'];
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', rtrim($path, '/'));
$campus = $segments[1];
$prog_parent = get_field('program_parent');
$prog_code = get_field('program_code');
$program_parent = $post->post_parent;
$prog_par_details = get_field('program_code', $program_parent );
if( $prog_parent == true ) {
$program = $prog_code;
} else {
$program = $prog_par_details;
}
return array($program, $campus);
}
And in my template I call the function in this way:
<?php
programpagedata();
echo $program;
echo $campus;
?>
So for example in my template I can call those function in this way:
<div class="form-group">
<label for="program">
<input type="hidden" class="form-control" id="program" aria-describedby="programHelp" placeholder="Program" value="<?php echo $program; ?>" name="program">
</label>
</div>
<div class="form-group">
<label for="campus">
<input type="hidden" class="form-control" id="campus" aria-describedby="campusHelp" placeholder="Campus" value="<?php echo $campus; ?>" name="campus">
</label>
</div>
I'm trying to understand where my mistake is, because, as I said, if I put this PHP snippet in my template, the code works fine with an important difference:
PHP IN THE TEMPLATE
<?php
global $post;
$url = $_SERVER['REQUEST_URI'];
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', rtrim($path, '/'));
$campus = $segments[1];
// $program = end($segments);
$prog_parent = get_field('program_parent');
$prog_code = get_field('program_code');
$program_parent = $post->post_parent;
$prog_par_details = get_field('program_code', $program_parent );
if( $prog_parent == true ) {
$program = $prog_code;
} else {
$program = $prog_par_details;
}
?>
<form>
my template form
</form>
?>
I don't return anything. So I guess that I'm struggling with the return keyword on WP. Any thoughts?
I think your problem is that you call the function, but you don't save the return to a variable, then you try to echo variables which don't only exist within the scope of the function.
When you return something from a function in PHP, you have to store that value inside a variable to use it, and variables created inside a function do not exist on the page the function was ran on.
Try this:
//Direct replacement of your template code, doesn't require modification to your function
//store return from function
$return = programpagedata();
//arrays start at 0, and $program is stored at index 0 of $return
echo $return[0];
//$campus is stored at index 1 of $return
echo $return[1];
It would probably be better to index your return with that the value actually is, instead of numbered indexes.
In your function, change your return to this:
function programpagedata() {
global $post;
...
return array("program" => $program, "campus" => $campus);
}
Then, you can call it this way:
//Template code if you modify `return` of function using snippet above
//store return from function
$data = programpagedata();
//$program is stored at index 'program' of $data
echo $data['program'];
//$campus is stored at index 'campus' of $data
echo $data['campus'];
You need to "catch" the return values.
list($program, $campus) = programpagedata();
echo $program;
echo $campus;
The variables that is used in a function does not exist anywhere else but in the function.
When you return values from a function you need to receive them to a variable in the main program.
In this case either as an array or as two listed variables
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.
I'm calling a specific function, either getTaskList0, getTaskList1, or getTaskList2, each the same as below, with the number after task referring to the getTaskList number (in TaskManagerDAO):
function getTaskList0(){
$lst=array();
$con=$this->getDBConnection();
$result = $con->query("SELECT name, score FROM task0 ORDER BY score DESC");
$i = 0;
$counter=0;
while (($row =$result->fetch_row()) && ($counter<5)) {
$rec = new Task($row[0],$row[1]);
$lst[$i++]=$rec;
$counter++;
}
return $lst;
}
Task:
<?php
class Task{
public $name;
public $score;
function __construct($name,$score) {
$this->name = $name;
$this->score = $score;
}
}
The function is called in here:
<?php
session_start();
if(!class_exists('Action')){
include_once 'Action.php';
}
if(!class_exists('TaskManagerDAO')){
include_once 'TaskManagerDAO.php';
}
class Action_DisplayList implements Action{
public function execute($request){
if(!isset($_SESSION['functCount']))
$_SESSION['functCount']=0;
$functCount=$_SESSION['functCount'];
$functionName="getTaskList{$functCount}";
echo $functionName;
$dao = new TaskManagerDAO();
$names = $dao->$functionName();
$_SESSION['names'] = $names;
$last = sizeof($names);
$start = 0;
$_SESSION['start'] = $start;
$_SESSION['last'] =$last;
header("Location: tasklist.php");
}
}
?>
I'm trying to call the function by putting a variable at the end of the function name as a string and then calling the function. This works as I don't get any errors, but the list does not show up in the table, which is what this code is supposed to do:
<?php
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
include 'Action_Add.php';
Action_Add::execute();
}
$functCount=0;
$_SESSION['functCount']=0;
$names = $_SESSION['names'];
$start=$_SESSION['start'];
$last = $_SESSION['last'];
for($count = $start; $count < $last; $count++){
$name=$names[$count];
echo "<tr>";
echo "<td>".($count+1)."</td>";
echo "<td>".$name->name."</td>";
echo "<td>".$name->score."</td>";
echo "</tr>";
}
?>
EDIT:
I restarted my computer and everything and for the first run load of the page it worked perfectly. After that though, it stopped working though.
Use session_start(); before start using $_SESSION. So in your case, try something like
<?php
session_start();
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
//.... remaining code here
Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
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.
In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.