Maybe my question is somehow elementary or stupid, however i need to verify this.
I have a php function "functionA" which is repeatedely called in a for loop:
...
for($j=0; $j<$n_samples;$j++) {
if($type=='triband') {
functionA($arg1,$arg2);
}
}
...
and my functionA:
...
functionA($arg1,$arg2) {
$wide_avg_txon = substr($bit_sequence,0,1);
if($wide_avg_txon==0)
{
echo " ---> is OFF...<br />";
}
else
{
echo " ---> is ON...<br />";
// if is ON then skip execution of code inside the function
return;
}
// DO SOME STUFF!
}
...
So simply i do not want to execute the rest of code inside functionA if "$wide_avg_txon==1" and i just want to continue executing the for loop for the next iteration!
Is the above code going to work? What is the difference between: 'return' and 'return false'? Is 'return false' going also to work:
...
if($wide_avg_txon==0)
{
echo " ---> is OFF...<br />";
}
else
{
echo " ---> is ON...<br />";
// if is ON then skip execution of code inside the function
return false;
}
thanks!
Your return will work because you are not interested in the result that is being returned. You just want to continue the for-loop.
If you had a code construction that tested something and you want to know the result of the testing then you could use return false to let the rest of the code know the test failed.
Your functionA will work perfectly, but for readability's sake it may be better to format it this way:
...
function functionA($arg1, $arg2) {
$wide_avg_txon = substr($bit_sequence,0,1);
// if is ON then skip execution of code inside this function
if ($wide_avg_txon != 0) {
echo " ---> is ON...<br />";
return;
}
echo " ---> is OFF...<br />";
// DO SOME STUFF!
}
...
The difference is that you immediately disqualify the "ON" condition that you don't want, and exit the function as quickly as possible. Then the rest of the function is working on whatever it is you want to do, rather that sitting inside of an if statement block.
Function will be stopped after the return statement. You can read more about here:
http://php.net/manual/tr/function.return.php
As as example you can do something like this to test this:
<?php
$_SESSION['a'] = "Naber";
function a(){
return;
unset($_SESSION['a']);
}
a(); // Let see that is session unset?
echo $_SESSION['a'];
?>
Thanks
return false returns false, a boolean. return will return NULL. Neither will execute any subsequent code.
So to expand upon RST's answer, both returns would not satisfy an if condition:
if(functionA($arg1,$arg2))
echo'foo';
else
echo'bar';
bar would be echoed.
Where this might be useful is if you have:
$return=functionA($arg1,$arg2);
if($return===NULL)
echo'Nothing happened';
elseif($return===false)
echo'Something happened and it was false';
else
echo'Something happened and it was true';
NULL is pretty useful.
Related
i want to continue my for-loop if called function execute exit(); statement.
Note:
Remaining code lines should not be processed when $i=2; so, the main thing i need help to exit my function but not for-loop.
Moreover, i have lot of conditions so i can not use if-else.
i have already tried return; statement but with the return; statement function executes remaining lines of code that's the main issue!.
Any help will be highly appreciated!
For example
for($i=0;$i<=5;$i++){
$this->calculate($i);
}
function calculate($counter){
if($counter==2){
exit(0);
}
echo "My remaining code lines";
}
UPDATED ANSWER
After your comment. We have to let the for loop know that we don't want to continue. Since the logic is separated we can do something like:
for ($i = 0; $i <= 5; $i++) {
if ($this->calculate($i) == false) {
break;
}
}
function calculate($counter) {
if ($counter == 2) {
return false;
}
echo "My remaining code lines";
return true;
}
ORIGINAL ANSWER
Do not exit the function. It halts any further processing.
Simply return:
function calculate($counter){
if($counter==2){
return;
}
Instead of exit use return because exit terminates the execution, whilst return only exists the current function.
And instead of if-else you can use swtich-case, like this:
for($i=0;$i<=5;$i++){
if(!$this->calculate($i))
{
continue;
}
}
function calculate($counter){
switch($counter){
case 2:
return false;
default:
echo "My remaining code lines";
break;
}
}
Edit: I have updated my answer to move the loop to next iteration if the method calculate() returns false.
return statement used.
for(condition){
return();
}
Just use a return instead. It will return to the caller and hence you can continue execution.
for($i=0;$i<=5;$i++){
$this->calculate($i);
}
function calculate($counter){
if($counter==2){
return;
}
echo "My remaining code lines";
}
// use return() function .. exit() stop execution ...
function calculate($counter){
if($counter==2){
return;
}
echo "My remaining code lines";
}
?>
Is there a way to have PHP discontinue execution of a class if my error variable (not a PHP error but a error set when input is invalid) is ever set without constantly checking the error variable? like a passive listener? My script has many places a error could occur. Something like this:
if(empty($this->error)) $this->error= function1();
if(empty($this->error)) $this->error= function2();
if(empty($this->error)) $this->error= function3();
$this->error is always returned a null value unless a error occurs. if it is ever not null I want exit the rest of the function with out having to put if(empty($this->error)) in front of everything.
Edit: farther explanation:
I suppose I want something that automatically checks if $this->error is empty after every line of code, without me telling it to, then exits the function if it's not empty, like a break in a loop.
the suggested posts do not solve my problem as they still require the condition be manually checked. I want something like this:
stays_empty($this->error)
{
$this->error= function1();
//PHP checks if $this->error is still empty. Continue if it is, break if it's not.
$this->error= function2();
//PHP checks if $this->error is still empty. Continue if it is, break if it's not.
$this->error= function3();
//PHP checks if $this->error is still empty. Continue if it is, break if it's not.
}
When doing repetitive actions, you should consider using loops instead of repeating code many times.
Many may not know this, but you can actually use variables a function names too as shown in this example.
<?php
class Whatever
{
function __construct() {
// Names of the functions we wish to run
$functionNameList = ['function1', 'function2', 'function3'];
// Looping our function names
foreach ($functionNameList as $key => $functionName) {
// Inserting variable as function name
$this->error = $this->$functionName();
if ($this->error) {
echo 'Error found ';
break; // This would break out of the foreach loop [OR]
return; // This will break out of the function
}
}
}
public function function1() {
echo 1;
return '';
}
public function function2() {
echo 2;
return 'error';
}
public function function3() {
echo 3;
return '';
}
}
$x = new Whatever();
You could also use exceptions as mentioned in other answers, but I'm answering your question in a fashion suitable for any situation with lots of repetition.
Edit: Short Version
$functionNameList = ['function1', 'function2', 'function3'];
foreach ($functionNameList as $key => $functionName) {
$this->error = $this->$functionName();
if ($this->error) {
break;
}
}
Edit: Super Short Version (Not as clear)
$functionNameList = ['function1', 'function2', 'function3'];
foreach ($functionNameList as $key => $functionName) {
if ($this->error = $this->$functionName()) {
break;
}
}
What are the best usages of functions that end with "return;" and what are the advantages of writing a function that ends this way?
Example:
function MyFunction() {
// (do something)
return;
}
Thank you
You shouldn't, I would always use return null; so that it is an explicit declaration of what is returned (even if it is null). I'm sure this is also in one of the PSR specs as well, but I don't know them well. To confirm that return; === return null;:
function test() {
return;
}
var_dump(test());
// NULL
As to when you would want to return null;..any function that returns something, should always return something. So maybe if you have a function that gathers and returns a value from a DB, and an error occurs:
public function retrieveData()
{
$data = DB::retrieve();
if(!$data) {
return null;
}
return $data;
}
However, a lot of functions that may have errors just return true/false on success or failure so you won't necessarily use this often.
My main point to drive home: if you don't want/need to return anything, don't return anything.
A return; says only "thats the end". Mostly useful in following examples:
function test($string) {
if(empty($string)) {
return; // If the variable is empty, then stop to work!
}
echo $string;
}
A simple example is that you can write a PHP function that spits out formatted HTML:
function printHeader($value)
{
echo "<h1>$value</h1>";
return;
}
However, since you are not returning anything, the return statement is unnecessary and can be left out.
If you are talking about a empty return;, I can think of one example, if you have code that should be executed under a condition, and more code that should be executed if that condition is not met.
function MyFunction() {
if(a < 1) {
// (do something)
return;
}
// If a >= 0 it executes the code above and the code below
// Do something else
}
I have checked a few other questions but they don't really give me the answer I expect..
My code is a like this..
private function handle()
{
if()
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
if(!condition))
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
code
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
}
In my opinion it is readable but messy, sadly I haven't found really a way of making it look 'pretty'. Any ideas?
EDIT: Each return is different.
EDIT2: Gave an answer of my own, thanks everybody!
Conditions can be merged by a && operator..It works form left to right, which means, as soon as the any one starting from left fails, it stops evaluating the condition..
if($a) {
if($b) {
}
}
can be replaced by
if($a && $b) {
}
Use a variable check, or combine the conditions into fewer IF statements.
Variable check like so:
$execute = TRUE;
// Opposite of what you want, e.g. if you want $a only to be TRUE, do $a !== TRUE
if (condition) {
$execute = FALSE;
}
...
// If all the conditions were met, then everything is OK
if($execute === TRUE) {
// code
}else {
// return
}
Edit:
Variable check can be preferably to combining IF statements if you want more control on what returns, e.g. something specific happens if a certain condition fails, which combining conditions can not always allow for.
Like already posted use
if(condition1&&condition2){}
or if this will not work, you can also use function which stops as soon as a condition is true
function some(){
if(!conditon 1){return 0;}
if(condition 2) {return 1;}
}
this provides more power as second if works only if first doesn't satisfy.
You must choose based on your requirements. Sometimes though nested loops are unavoidable.
I thought it out and have found a nice way of doing it, basically I'll make a method for each basic condition, and I'll call them in an if statement with the bitwise AND operator (&), which don't short-circuit.
/**
* nonsql_condition - It means it doesn't check with the database
*
* sql_condition - It means it does check with the database.
*/
if(!$this->nonsql_condition() & !$this->nonsql_condition() & !$this->nonsql_condition() & !$this->nonsql_condition())
{
if(!$this->sql_condition())
{
return error;
}
if(!$this->sql_condition())
{
return error;
}
code;
}
This allows me to use fewer lines of code in my method, plus also not doing unnecessary queries to my database.
so I have 2 functions like this:
function boo(){
return "boo";
}
and
function foo(){
echo "foo";
}
the fist one will return a value, and the 2nd one will output something to the screen directly.
$var = boo();
foo();
How can I merge these 2 functions into one, and somehow detect if it's being called to output the result to the screen, or if it's called for getting the return value? Then choose to use return or echo...
function boo_or_foo ($output = false) {
if ($output) {
echo "fbo";
} else {
return "foo";
}
}
But whats the benefit against just using one function (boo()) and echo it yourself?
echo $boo();
Well, a function should only do one thing, so typically you would have two functions. But, if you would like to combine them you can just check if is set:
function boo($var=null){
if(isset($var)) echo $var
else return "boo";
}
well return true in the function that prints then yo just do
function foo(){
echo "foo";
return true;
}
if(foo()){
echo "foo did print something";
}else{
echo "nope foo is broken";
}
I wanted to achieve the same effect. In my case I have functions that produce HTML which I want echoed directly sometimes (when an Ajax call is being made), or returned (when a call is made from another script).
For example, a function that creates a list of HTML <option> elements - listOfOption($filter). When one of my pages is first created, the function is called and the result is echoed in place:
<?= listOfOption($var) ?>
But sometimes the same data needs to be retrieved in an Ajax call:
http://site.com/listOfOption.php?parameter=2
Instead of writing two different scripts or specifying the behaviour in a parameter, I keep listOfOption($filter) in its own file like this:
if (__FILE__ == $_SERVER['SCRIPT_FILENAME'])
{
echo listOfOption($_REQUEST['parameter']);
}
function listOfOption($filter)
{
return '<option value="1">Foo</option>';
}
This way if the call is from another script, it returns the data; otherwise it prints the data.
Note that if a parameter isn't passed to the function I wouldn't have to do this, I could live with echoing the data always and replacing the <?= listOfOption() ?> invocation with <? listOfOption() ?> to keep things clear.