Jump to content

include and echo problem


Linjon

Recommended Posts

Hello.

I made 2 php files, echo.php and variable.php.

echo.php:

<?php
include ('variable.php');
echo "Random number is: $variable"; 
?>

 

variable.php:

<?php
function genRandomString() {
    $length = 10;
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ”;    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $variable;
}

?>

 

And here is the question. Why echo showing only "Random number is:"  ? Where is the problem?

Link to comment
https://forums.phpfreaks.com/topic/239684-include-and-echo-problem/
Share on other sites

try

echo "Random number is: ".genRandomString(); 

 

 

instead..

 


 

What you include doesn't "pre-fill" any variables, it just includes the code you specify in the included file, into the main page (with some restrictions, ofcourse)

 

if you want $variable in the other page, you will need to do something like this

 

echo.php

<?php
include('variable.php');
echo $variable;
?>

 

variable.php

<?php
function abc() {
  return 'xyz';
}
$variable = abc();
?>

echo.php:

<?php
include ('variable.php');
echo "Random number is: $variable"; 
?>

 

variable.php:

<?php
function genRandomString() {
    $length = 10;
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ”;    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $variable;
}

?>

 

Hope this helps! :)

 

<?php
include ('variable.php');
echo "Random number is: ".genRandomString()."";
?>

 

<?php
function genRandomString() {
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = "";    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}?>

Just so you know, the reason your page that includes "variable.php" doesn't have access to $variable is because of scope. WHen inside a function, the function only has access to local variables created in the function body, and arguments passed into the argument list. Likewise, when outside of a function, the local variables and arguments inside a function don't exist. So if we had

function f(){
$str = "Hello World!";
}
echo "string: ". $str;

this would output

string: 

 

Why? because $str is local to the function f(), so its unavailable (and doesn't even exist as far as PHP is concerned) outside of it.[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.