user4214050
user4214050

Reputation:

Global variables use

I can't understand how they operate global variables in this language, I read the documentation and everything is explained clearly, but when I go to apply via this code does not work. Probably something I'm wrong, help me to correct.

I declare a variable within the spreadsheet php, I call the variable $pubblica at this point I'm going inside a function to insert the content in this way:

function add()
{
    $GLOBALS['pubblica'] = "insert name";
}

I imagine that the content of the variable $pubblica now is: "insert name" I therefore the need to use the variable with this content inside another function like this:

function esplore()
{
    echo "Contents of variables is $pubblica";
}

Should print me this content: "insert name"; But I get a blank message, and do not understand why. What's wrong with that?

UPDATE QUESTION:

<?php

$GLOBALS['pubblica'];

function add()
{
   $GLOBALS['pubblica'] ="insert name";
}

function esplore()
{
   echo "Contents of variables is " . $GLOBALS['pubblica'];
}

?>

the add function is activated when you press a button, and within this is called esplore

Upvotes: 0

Views: 93

Answers (2)

John
John

Reputation: 123

The problem is you use form to pass the data. So Global variables get lost. You need to retrieve your FORM variables.

The script below will let you enter your variable in the input field and on submit will keep it and display the result.

<?php
$publicca=(isset($_POST['publicca']) ? $_POST['publicca'] : "");
// we check if there is the variable publicca posted from the form, if not $publicca is empty string
?>

<form action="#" method="post">
<input type="text" name="pubblica" value="<? echo $publicca; ?>" placeholder="insert name">
<!-- this input can be hidden, or visible or given by user, different formats, this is an example of user input -->
<button type="submit"> Pres to send the values </button>

<?

function esplore()
{
    global $pubblica;
    if (!empty($publicca)) echo "Contents of variables is $pubblica";
}
esplore();
?>

Upvotes: 0

user7000326
user7000326

Reputation:

What you are looking for is:

<?php
function add()
{
    $GLOBALS['pubblica'] = "insert name";
}

function esplore()
{
    global $pubblica;
    echo "Contents of variables is $pubblica";
}

add();
esplore();
?>

If you don't use global $pubblica; the esplore() function doesn't know that $pubblica is a global variable and tries to find it in the local scope.

A different story would be:

function esplore()
{
    echo "Contents of variables is " . $GLOBALS['pubblica'];
}

In this case it's obvious that you are addressing a (super-) global variable and no additional scope hinting is required.

Upvotes: 1

Related Questions