PHP return string without "echo"? - php

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!

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();

Get values from vars inside class across other functions

class dir_exam
{
public $db_ruta;
function __construct($db_ruta)
{
$this->db_ruta=$db_ruta;
}
function veritas()
{
$aa="ok";
$xx="ok2";
return $aa;
return $xx;
}
function create_d()
{
$r=$this->veritas();
echo $r->$aa;
echo $r->$xx;
}
}
I have this class and i try execute funtion veritas inside function create_d, but i want show the value from function veritas as individual values, showing value in create_d for $aa and $xx, when execute finally the class
<?php
$a=new dir_exam("db_p");
echo $a->create_d();
?>
But i can´t get this finally, i don´t know if it´s not possible or what, this it´s my question, thank´s in advanced
You can't have 2 or more returns in a function.
For you use the vars $aa and $xx like OOP, you must create the 2 var in the class
class dir_exam
{
public $db_ruta;
public $aa; // <--
public $xx; // <--
}
After, you need change the function veritas to pass the value for your attributes
function veritas()
{
$this->aa="ok";
$this->xx="ok2";
}
Now in your function you can call like that:
function create_d()
{
$this->veritas();
echo $this->aa;
echo $this->xx;
}

PHP/Laravel How to include one function into another?

Is there a way I can include(?) one function into another? For example, the same way we can include files using include function.
Thank you.
<?php
class test{
public function message1(){
$message = 'i am in message1 function';
return $message;
}
public function message2(){
$message = $this->message1();
echo $message;
}
}
Functions can not be "included" like you mean but you can call them and use their returned values to other functions like below.
Now if you try to call the message2 function using something like:
$messageClass = new test();
echo $messageClass->message2();
you will see that the output is the $message from function message1
Do you mean callback function? If so, this is how to use it:
// This is callback function which will passed as argument to another function.
function callbackFunction1 ($str) {
return strtoupper($str);
}
function mainFunction ($offeredCallback, $str) {
echo( "(" . $offeredCallback($str) . ")<br>");
}
mainFunction("callbackFunction1", "foo");
// Output "(foo)".
// If you want to use Variable Function, define it like this:
$callbackFunction2 = function ($str) {
return strtoupper($str);
};
mainFunction($callbackFunction2, "bar");
// Output "(bar)".
About Variable Function, see Anonymous Function.

PHP Error: Class::__toString() must return a string value in

This is a __toString() method I'm trying to use in a PHP class. It throws the error "Catchable fatal error: Method Project::__toString() must return a string value in..."
But as far as I can tell, everything I'm passing it is a string. I even checked the $this->proj_id with gettype($var) to confirm it's a string, and it is.
Here is the Project class...
class Project {
public $proj_id;
public $proj_num;
public $proj_name;
public function __construct($id, $num, $name){
$this->proj_id = $id;
$this->proj_num = $num;
$this->proj_name = $name;
}
public function __toString(){
echo "<table>";
echo "<tr><td>".'proj_id: '."</td><td> ".$this->proj_id." </td><t/r>";
echo "</table><br><br>";
}
}
And here is the object instantiation...
$test_obj = new Project('XC2344','HKSTEST','Test Project');
echo $test_obj; //this is where the error shows up - even though it actually outputs the table with the correct value in both cells ?!
It actually outputs the table and cells and values in those cells just as I want it to, but then gives the error and stops creating the rest of the webpage. I don't get it.
when you call echo on your Project object, the object is transformed into a string which will be used for outputting. If you define __toString method by yourself, it has to return a string that has to be outputted. Instead of outputting string right away in the __toString method, just return it.
public function __toString(){
return "<table>" .
"<tr><td>".'proj_id: '."</td><td> ".$this->proj_id." </td><t/r>" .
"</table><br><br>";
}
So when you call
echo $test_obj;
The __toString will be called, your function will return the string, and echo will output it.
__toString() must return a string, not echo it:
public function __toString(){
return "<table>"
. "<tr><td>".'proj_id: '."</td><td> ". $this->proj_id. " </td><t/r>"
. "</table><br><br>"
}
Echoing is not the only use of a string. Maybe you want to save the object to a database, or put it into a JSON structure.
__toString must return a string, not output content.
public function __toString(){
$str = "<table>";
$str .= "<tr><td>".'proj_id: '."</td><td> ".$this->proj_id." </td><t/r>";
$str .= "</table><br><br>";
return $str;
}

method does not get passed when passing the class? PHP

What I want to ask is,
let's say I have a class Info and there's a getter in the info called getABC()
In a controller I assigned something like
$info = new Info();
$variable['info'] =$info;
and $variable is being passed into the view.
In the view, am I able to use something like $variable['info']->getABC() ?
I know I can just test it out myself, and failed saying something like it did not exist and $variable['info'] does show something though.
I just want to make sure that $variable['info']->getABC() is suppose to NOT work or it should but I am just doing something wrong that's why I couldn't get what's needed.
actual code below........
Class
class CreditCardPayment{
private $_card_type = '';
private $_card_number = '';
private $_card_number_last_4 = '';
public function setCardType($v)
{
$this->_card_type = $v;
return $this;
}
public function setCardNumber($v)
{
$this->_card_number = $v;
return $this;
}
public function setCardNumberLast4($v) {
$lastFourDigits = substr($v, -4);
$output = 'xxxx-xxxx-xxxx-' . $lastFourDigits;
$this->_card_number_last_4 = $output;
return $this;
}
public function getCardType() {
return $this->_card_type;
}
public function getCardNumber() {
return $this->_card_number;
}
public function getCardNumberLast4() {
return $this->_card_number_last_4;
}
}
and in Controller let's say when it's successful....it'll be something like this where $creditCardPayment = new CreditCardPayment and I tried var_dump($creditCardPayment) that definitely info is all filled and of course those are private variables so I had to use the getter retrieve them.
Controller
$ordermess['creditCardPaymentInfo'] = $creditCardPayment;
\Yii::$app->session->set('ordermess', $ordermess);
$this->redirect('/pay/completed');
then in my view...I did this as testing
<?php
echo '<pre>';
echo ($ordermess['creditCardPaymentInfo']->getCardNumberLast4());
echo '</pre>';
die;
?>
then when I load the page I would get error.
Call to a member function getCardNumberLast4() on a non-object
Yes. It is supposed to work. If there is sanitization code in the function assigning variables to the view, it could be converting the object to an array.

Categories