How to echo a function response in php - php

I created a function to check for special characters in a string, but I can't seem to get it to echo the response message
Here is my code
<?php
function chk_string($string){
if (preg_match('/[\^£$%&*()}{##~?><>|=_+¬-]/', $string))
{
$chk_str="false";
} else {
$chk_str="true";
}
return $chk_str;
}
$string="this is just a test" ;
chk_string($string) ;
echo $chk_str;
?>
The "echo $chk_str" is not echoing anything.

If you did
$chk_str = chk_string($string);
then you could echo $chk_str;.
The $chk_str you are trying to echo is only visible in your function.
More description:
Your function (chk_string) is in a different scope than your echo.
Your function returns a variable, but that variable is "lost", since you don't assign it to another variable.
Your code currently does something like this line by line:
Your function declaration
$string means "this is just a test"
your functions result as a string, just floating in the code
write out a variable that doesn't exist.
I hope this helped in someway.

You need to store returned value in a particular variable if you want to echo that variable like this,
$chk_str = chk_string($string) ;
echo $chk_str;
Another way you can just directly echo returned value like this,
echo chk_string($string) ;

Your question is about variable scope and it is answered already, but I would recommend you to take a look at variable scope here https://www.php.net/manual/en/language.variables.scope.php.
Basically, every variable has its scope and we can not access a variable outside its scope. In your case, scope of variable $chk_str is inside function chk_string so you can not access it outside of the function. Because you return value of $chk_str in function chk_string so you still can access its value through response of function chk_string, for example:
echo chk_string('a string');
OR
$result = chk_string('a string');
echo $result;

Related

PHP - set a variable which does not neet to call using global

I have a variable called
$variable
And when I call it inside a function then I need to use
some_function(){
global $variable;
echo $variable['array'];
}
But I dont want to use a global every time, Is there a way so by which I can call variable without setting a global everytime???
Thanks for your time.
standard practice ...
some_function($variable){
echo $variable['array'];
}
called like any other function:
some_function($variable);
You can Pass it as a parameter to your function
$variable=array(2,5,6,9,7);
some_function($param){
print_r($param); // this is your variable
}
call it like
some_function($variable);
In case you don't want to use "global", you may use $GLOBALS superglobal variable:
function some_function() {
echo $GLOBALS['variable']['array'];
}
$GLOBALS is an associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
http://www.php.net/manual/en/reserved.variables.globals.php

get return value from a function php using oops

I have code below, where i need to get the return value in a variable outside a class and also its print with respective code.
http://codepad.org/mAlhYBll
and below is raw code.
<?php
class test {
public function kk() {
echo "Whats up :";
return "Hello";
}
}
$obj = new test();
$obj->kk();
$abc = $obj->kk();
?>
Now how can i get value returned from a function added an image below
You need to echo $abc. The program is printing something else since you're echoing What's up within the method, remove that.
Exactly as you've done - although you call "kk()" twice, which is not nneeded, so drop line 13.

PHP Basics: Can't deal with scope within classes

i got some trouble to understand scope in OOP. What i want is that $foo->test_item() prints "teststring"...Now it just fails with:
Warning: Missing argument 1 for testing::test_item()
Thanks a lot!
<?php
class testing {
public $vari = "teststring";
function test_item($vari){ //$this->vari doesn't work either
print $vari;
}
}
$foo = new testing();
$foo->test_item();
?>
test_item() should be:
function test_item() {
print $this->vari;
}
There is no need to pass $vari as a parameter.
Well, you've declared a method which expects an argument, which is missing. You should do:
$foo->test_item("Something");
As for the $this->, that goes inside of the class methods.
function test_item(){
print $this->vari;
}
function parameters can not be as "$this->var",
change your class like
class testing {
public $vari = "teststring";
function test_item(){ //$this->vari doesn't work either
print $this->vari;
}
}
$foo = new testing();
$foo->test_item();
And read this Object-Oriented PHP for Beginners
What's happening there is that $foo->test_item() is expecting something passed as an argument, so for example
$foo->test_item("Hello");
Would be correct in this case. This would print Hello
But, you may be wondering why it doesn't print teststring. This is because by calling
print $vari;
you are only printing the variable that has been passed to $foo->test_item()
However, if instead you do
function test_item(){ //notice I've removed the argument passed to test_item here...
print $this->vari;
}
You will instead be printing the value of the class property $vari. Use $this->... to call functions or variables within the scope of the class. If you try it without $this-> then PHP will look for that variable within the function's local scope

What does & sign mean in front of a variable?

I'm 'dissecting' PunBB, and one of its functions checks the structure of BBCode tags and fix simple mistakes where possible:
function preparse_tags($text, &$errors, $is_signature = false)
What does the & in front of the $error variable mean?
It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.
function passByReference(&$test) {
$test = "Changed!";
}
function passByValue($test) {
$test = "a change here will not affect the original variable";
}
$test = 'Unchanged';
echo $test . PHP_EOL;
passByValue($test);
echo $test . PHP_EOL;
passByReference($test);
echo $test . PHP_EOL;
Output:
Unchanged
Unchanged
Changed!
It does pass by reference rather than pass by value.
This allows for the function to change variables outside of its own scope, in the scope of the calling function.
For instance:
function addOne( &$val ) {
$val++;
}
$a = 1;
addOne($a);
echo $a; // Will echo '2'.
In the case of the preparse_tags function, it allows the function to return the parsed tags, but allow the calling parent to get any errors without having to check the format/type of the returned value.
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $errors = "Error!") will affect the variable passed by the calling function.
It means that the variable passed in the errors position will be modified by the called function. See this for a detailed look.

My PHP Function isn't working

I'm having trouble with the following code. What it should do is echo cats.php followed by example.php but it's not echoing the example.php. Any ideas why this might be happening?
$bookLocations = array(
'example.php',
'cats.php',
'dogs.php',
'fires.php',
'monkeys.php',
'birds.php',
);
echo $bookLocations[1];
function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}
findfile(0);
Try changing,
echo $bookLocations["$filenumber"];
to:
echo $bookLocations[$filenumber];
Edit* To expand on Thomas's correct answer, instead of using global variables, you could change your method to:
function findfile($filenumber, $bookLocations)
{
echo $bookLocations[$filenumber];
}
i believe you may also need to declare the global variable in your function.
global $bookLocations;
Ok, there are two issues.
Variable Scope
Your function doesn't know the array $bookLocations, you need to pass it to your function like so:
function findfile($filenumber, $bookLocations)
Array key
You don't want to wrap your array key in quotes:
wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];
The quotes in "$filenumber" turn your key into a string, when the keys to your array are all numbers. You are trying to access $bookLocations["1"] when in fact you want to access $bookLocations[1] -- that is to say, 1 is not the same as "1". Therefore, like others have said, you need to get rid of the quotation marks around the key (and check your variable scope too).
function findfile($filenumber)
{
global $bookLocations;
echo $bookLocations[$filenumber];
}
Good-style developers usually avoid global variables. Instead, pass the array to the function as the parameter:
function findfile($files, $filenum)
{
echo $files[$filenum];
}
$bookLocations is out of scope for your function. If you echo $filenumber you will see that it's in scope because you passed it in by value. However, there is no reference to $bookoLocations.
You should pass in $bookLocations
declaration: function findfile($filenumber, $bookLocations){
call: findfile(1, $bookLocations);
You could also to declare $bookLocations as global, but globals should be avoided if possible.

Categories