Jump to content

[SOLVED] 'Scope'?


LemonInflux

Recommended Posts

A while back, one of my friends did a website, and they had written a function library. Nothing special, I'd done a few of my own functions, but he said he could use the functions without including the library. He said it was something to do with 'code scope'. I tried to find some easy explanations, but they all seem very complex. Is there a simple way to use this? Or, is it the wrong word?

Link to comment
https://forums.phpfreaks.com/topic/76003-solved-scope/
Share on other sites

There is no way to use an external function (stored in a separate library) without including it. You can include it via including the library script, or copy/paste the single function you need from the library directly into your script.

 

Scope is used to define when a variable retains its previous set value, or 'state'.

 

<?php
$a = 'this';
$b = 'that';

echo "a = $a<br />"; // prints this
echo "b = $b<br />"; // prints that
echo "this_n_that says:<br />";
print_this_n_that(); // does nothing, because $a and $b do not have scope within the function
echo "this_n_that2 says:<br />";
print_this_n_that2(); // prints this and that because you have passed scope to the function via global.

function print_this_n_that() {
echo "a = $a<br />"; // prints nothing ($a has no scope)
echo "b = $b<br />"; // prints nothing ($b has no scope)

}

function print_this_n_that2() {
global $a, $b;
echo "a = $a<br />"; // prints this
echo "b = $b<br />"; // prints that

}
?>

 

PhREEEk

Link to comment
https://forums.phpfreaks.com/topic/76003-solved-scope/#findComment-384698
Share on other sites

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.