Closure behaving unexpectedly - php

I have a closure inside a function but when it is called the return value is not where i expected it to be.
public function test($name, $content)
{
$test = "\t<div id=\"{$name}\">{$content()}</div>\n";
return $test;
}
Instead of returning this...
<div id="name">content</div>
It instead returns...
content
<div id="name"></div>
If you have any idea how to fix this to display properly then i would be a very happy man, thanks in advance.

You haven't showed the $content() function, but from the symptoms I assume it prints the content instead of returning it. What happens is that the test() function calls the $content() function which displays the content and returns nothing, then test() returns and something else prints the return value.
To fix it simply have $content() return the content instead of printing it.

Let the closure execute and catch what's returned. Then insert the result:
public function test($name, $content)
{
$insert = $content();
$test = "\t<div id=\"{$name}\">{$insert}</div>\n";
return $test;
}

Related

PHP function working differently for return and echo. Why?

By using the following class:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
$trimmed=trim($form);
$specialchar=htmlspecialchars($trimmed);
$finaloutput=stripslashes($specialchar);
echo $finaloutput;
}
public function __destruct()
{
unset($finaloutput);
}
}
and Calling the function, by the following code, it works fine.
<?php
require('source/class.php');
$target="<script></script><br/>";
$forminput=new SafeGuardInput($target);
?>
But if in the SafeGuardInput class if I replace echo $finaloutput; with return $finaloutput; and then echo $forminput; on the index.php page. It DOES NOT WORK. Please provide a solution.
You can't return anything from a constructor. The new keyword always causes the newly created object to be assigned to the variable on the left side of the statement. So the variable you've used is already taken. Once you remember that, you quickly realise there is nowhere to put anything else that would be returned from the constructor!
A valid approach would be to write a function which will output the data when requested:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
}
public function getFinalOutput()
{
$trimmed = trim($this->form);
$specialchar = htmlspecialchars($trimmed);
$finaloutput = stripslashes($specialchar);
return $finaloutput;
}
}
Then you can call it like in the normal way like this:
$obj = new SafeGuardInput($target);
echo $obj->getFinalOutput();

PHP return string without "echo"?

I have a class containing a lot of "return" functions :
Class Components_superclass
{
public function build()
{
$this->add_category('Grille');
}
public function add_category($name)
{
return '<div class="category">'. $name .'</div>';
}
...
}
I want to get the html code containing in "add_category" function. But when I echo this, I have nothing :
$component = new Components_superclass();
echo $component->build();
Must I add "return" in build function ? Is there a way to avoid this ? Because I have a lot of function to call and I don't want to write something like this :
public function build()
{
return
$this->function_1() .
$this->function_2() .
$this->function_3();
}
Thanks !
Yes, the echo doesn't work because nothing is returned from build – there is not string that's passed into echo which could be printed.
About your second question, you could buffer the string internally and then return it at once, like this:
Class Components_superclass
{
private $buffer = array();
// …
public function add_category($name)
{
$this->buffer[] = '<div class="category">'. $name .'</div>';
}
public function output()
{
return implode('', $this->buffer);
}
}
If you want a function to return a value (that can be a string, integer or other types) use return. If you call the function, the returned value is then available on that place.
If function_1() return the string 'I am function one' and you echo the function call (echo $this->function_1();), the string 'I am function one' will be echoed.
This is also the correct way of working with functions. If you want to echo thing from inside the function, just echo in the function.
Check out PHP.net's function documentation!

Get two values returned from class

I am trying to understand object oriented PHP programming and wrote a small class to learn. I am having trouble understanding why its not working the way I intend. I have two variables inside the class method hello() $result and $test. I am trying to access the data that is stored in those two variables and print it to the screen. I know I can just call an echo inside the method but I am trying to get it to echo outside of it.
What I get printed to the screen is 88 it does not print out the second variable $test. I am trying to understand why thats happening. My lack of understanding probably shows in the code.
<?php
class simpleClass{
public function hello($result,$test) {
$result = 4+4;
$test = 10+5;
return $result;
return $test;
}
}
$a = new simpleClass;
echo $a->hello();
echo $a->hello($result, $test);
?>
you can return a list or array
public function hello($result,$test) {
$result = 4+4;
$test = 10+5;
return array($result, $test);
}
Use parameter referencing :
class simpleClass{
public function hello(&$result, &$test) {
$result = 4+4;
$test = 10+5;
}
}
$a = new simpleClass;
$result=''; $test='';
$a->hello($result, $test);
echo $result;
echo '<br>';
echo $test;
8
15
To clarify, when you add & to a function param, the value of that param - if you change or manipulate it inside the function - is handled back to your original variable passed. So you dont even have to return a result, and lets say pack it into an array or stdObject and unpack it afterwards. But you can still return something from the function, eg
$ok = $a->hello($result, $test);
as a flag to indicate if the calculation went right, for instance.
You cannot have multiple return statements in the same function because of the way return works. When a return statement is encountered the function stops executing there and then, passing back to the caller. The rest of the function never runs.
The complicated answer is to use a model.
class simpleResultTestModel {
public $result;
public $test;
public function __construct($result,$test) {
$this->result = $result;
$this->test = $test;
}
}
class simpleClass {
public function hello($result=4, $test=10) {
$result = $result+4;
$test = $test+5;
return new simpleResultTestModel($result, $test);
}
}
This way, you know simpleClass->hello() will always return an instance of simpleResultTestModel.
Also, I updated your hello method definition. You have two parameters, but don't actually apply them; I took the liberty of setting default values and then used them in the computation.
Usage:
$a = new simpleClass();
$first = $a->hello();
echo $first->result;
echo $first->test;
$second = $a->hello($first->result,$first->test);
echo $second->result;
echo $second->test;
I would try to stay away from passing by reference (especially within a class definition) unless you have a legitimate reason for doing so. It is bad practice when creating instances of classes (i.e. "sticky values" if you will).

How to determine if function doesn't return anything?

Is there a way to do this in PHP, using Reflection or something?
function a{
return null;
}
function b{
}
$a = a(); // null
$b = b(); // null :(
If you do not explicitly return something then functions will return null by default. That is just how functions work in PHP, and there is no way of finding out if the function has a return value.
This should not be a problem, though. If a function returns null it usually means that nothing was done, or that nothing was found, etc.
As you are defining your own functions, you should know yourself if they are returning anything or not.
By in any case. A function returns null by default unless you have overridden the return
function A (){
}
function B(){
return 'Test';
}
function C(){
return;
}
function CheckValidation ($Var){
if (is_null($Var)){
return 'Sample Is Null';
}else{
return 'Sample Is Not Null and returned a value!';
}
}
echo CheckValidation(A()); // Will output: 'Sample Is Null'
echo CheckValidation(B()); // Will output: 'Sample Is Not Null and has returned a value!
echo CheckValidation(C()); // Will output: 'Sample Is Null'
The function I have provided is the best you are going to get, due to the fact a function returns null by default if there is no return that is..
mind not to return it null because it will definitely display no results.
instead try to add an echo statement inside for checking or return it with a value but still in either case you still have to use echo to output results.....
Also refer to PHP.NET on proper way how to create a USER DEFINE FUNCTION

What is the order of operations with this function call?

<?php
class MyClass
{
static function test()
{
echo "Victor";
}
static function result()
{
echo "My name is ".self::test();
}
}
MyClass::result();
?>
I'm confused why self::test() is executed before the rest of the command or the other way around. Thanks in advance for the comments.
Because to get string that needs to be echoed out needs to be "prepared". so before output it needs to know what's the return value of it. it executes first and it's result is included in string. Actually, self::test(); does not return value, but echoes out some text.

Categories