EDIT: Link to my first question. Might clear some things up.
PHP Get corresponding data, with default and error handling
I have a function that checks if a GET statement exists. If so, it passes the value to a other function that then selects a class based on the value of the GET statement.
explaining:
The url = Page=Contact
The GetFormVariable approves it, and the class Contact is selected and it will give back a string. This string is used as an object 'Content' that, as it says, creats the content of the page.
public function getFormVariable($value){
switch (strtoupper($_SERVER['REQUEST_METHOD'])) {
case 'GET':
if (isset($_GET[$value]) && $_GET[$value] != NULL) {
return $_GET[$value];
}
else{
return false;
}
break;
case 'POST':
if (isset($POST[$value]) && $POST[$value] != NULL) {
return $POST[$value];
}
else{
return false;
}
break;
default:
return false;
}
}
Now the question.
When there is no GET statement in the url. The GetFormVariable returns false. And this means there is nothing shown.
How do i give this constructor.
public function SetProperty ($prob, $val){
$this->$prob = $val;
}
The information to create the ContentHome.
SetProperty('Content', 'ContentHome');
Sorry for poor explanation, if anything is unclear please tell me so.
I'm suggesting we close this question as unclear what you're asking, but decided to throw some help on the provided code sample anyway...
You can strip this down dramatically, and since there's no context, the function can be static too.
static public function getFormVariable($value)
{
if($_SERVER['REQUEST_METHOD'] == 'GET' &&
isset($_GET[$value]) &&
!empty($_GET[$value]))
return $_GET[$value];
elseif($_SERVER['REQUEST_METHOD'] == 'POST' &&
isset($POST[$value]) &&
!empty($POST[$value]))
return $POST[$value];
return false;
}
Your original isset and != NULL checks were doing the same check. Maybe you want the empty() check as a third check, but look it up to be certain.
The question is unclear.
How you call getFormVariable? How you use SetProperty with the information getFormVariable provides?
As far as I understood, you mean this...
$var = getFormVariable(???);
if (false === $var)
{
SetProperty('Content', 'ContentHome');
} else {
SetProperty('var', $var);
}
Related
I have this code in a function:
if ($route !== null) { // a route was found
$route->dispatch();
} else {
// show 404 page
$this->showErrorPage(404);
}
Now PHPmd gives an error:
The method run uses an else expression. Else is never necessary and
you can simplify the code to work without else.
Now I'm wondering if it really would be better code to avoid the else and just add a return statement to the if part?
PHPMD is expecting you to use an early return statement to avoid the else block. Something like the following.
function foo($access)
{
if ($access) {
return true;
}
return false;
}
You can suppress this warning by adding the following to your class doc block.
/**
* #SuppressWarnings(PHPMD.ElseExpression)
*/
You usually can rewrite the expression to use just an if and it does subjectively make the code more readable.
For example, this code will behave in the same way if showErrorPage breaks the execution of the code.
if ($route == null) {
$this->showErrorPage(404);
}
$route->dispatch();
If the content of your if statement does not break the execution, you could add a return
if ($route == null) {
$this->showErrorPage(404);
return;
}
$route->dispatch();
If you where inside a loop, you could skip that iteration using continue
foreach ($things as $thing ) {
if ($thing == null) {
//do stuff and skip loop iteration
continue;
}
//Things written from this point on act as "else"
}
I wouldn't worry about what PHPmd says , atleast in this case.
They probably meant for you to use the conditional operator because (in their opinion) its 'cleaner'.
$route !== null ? $route->dispatch() : $this->showErrorPage(404) ;
Remove the else block by ending the 404 producing branch:
if ($route === null) {
// show 404 page
$this->showErrorPage(404);
return;
}
// a route was found
$route->dispatch();
This answer is coming late, but another method you can get around that is by using else if. Because sometimes you cannot just return if some logic should follow.
Having your example
if ($route !== null) { // a route was found
$route->dispatch();
}
else if ($route === null) {
$this->showErrorPage(404);
}
$route->doSomething();
This is more or less a readability, maintainability and/or best practice type question.
I wanted to get the SO opinion on something. Is it bad practice to return from multiple points in a function? For example.
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== FALSE) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
} else {
return FALSE;
} else {
// returning false because $a->value isn't set
return FALSE;
}
}
?>
or should it be something like:
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== false) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
}
}
return FALSE
}
?>
As a matter of practice, I always try to return from ONE point in any function, which is usually the final point. I store it in a variable say $retVal and return it in the end of the function.It makes the code look more sane to me.
Having said that, there are circumstances where say, in your function as the first line you check if a var is null and if yes you are returning. In this case, there is no point in holdin on to that variable, then adding additional checks to skip all the function code to return that in the end.
So...in conclusion, both ways works. It always depends on what the situation is and what you are more comfortable with.
In PHP I need to pass some arguments to a function by reference.
I don't want to write 2 different methods for similar behaviour.
So i need to select behaviour by argument.
But I can't pass null by reference.
So I created a dummy array.
So i run it either by
$temp[0]=-1;
$this->doSomething($bigIds, $temp);
or
$temp[0]=-1;
$this->doSomething($temp, $smallIds);
public function doSomething(&$bigIds, &$smallIds) {
if ($bigIds[0] != -1) {
// make some thing
}
if ($smallIds[0] != -1) {
// make some thing
}
}
Is there a better/ elegant way to do this?
I would suggest an enum but this is PHP. So this should do it for you:
class YourClass
{
const DoSomethingSmall = 0;
const DoSomethingBig = 1;
public function doSomething(&$ids, $actionType) {
// can also use a switch here
if($actionType == self::DoSomethingSmall) {
// do small
}
else if($actionType == self::DoSomethingBig) {
// do big
}
}
}
Then you can do:
$this->doSomething($bigIds, self::DoSomethingBig);
$this->doSomething($smallIds, self::DoSomethingSmall);
From outside the class you can use YourClass::DoSomethingBig and YourClass::DoSomethingSmall
There could be loads of things you might rather do, for instance what #ad7six says in a comment, and you could also just give it some sort of setting and just one array..
public function doSomething(&$bIds, $mode) {
switch($mode){
case 1: do smallthing;break;
case 2: do bigthing;break;
case 3: do both;break;
default: do nothing;break;
}
It all depends on what you need really
I want to return multiple nested functions in PHP. It's possible to break out of multiple loops by adding a number after "break". Eg.
while(1)
while(1)
while(1)
break 3;
Can I do a circuit break while calling a sequence of functions?
Not that I know of, it's also not very healthy of a design, as the parent and grandparent functions in question will never know of the break. You should throw an exception and catch it on the parent, which in turn will throw an exception and catch it on the grandparent etc.
To "break" out of functions, you can use the return.
function somefunction()
{
return;
echo 'This will never get displayed';
}
Another solution would be to add a condition to each while.
while(1 && $isTrue)
while(1 && $isTrue)
while(1 && $isTrue)
$isTrue = false;
break;
Although I don't think this is a very clean approach.
As the manual states break is for loop only.
What I do in such cases is that have an exception return value(or object) and do value check on return value at every function return point to make sure that the situation is propagated or handled appropriately, be careful while doing recursions though, you might completely fold up the tree by mistake....btw if it is a simple exit on error kind of situation you can also use exceptions.
It's possible to return a special result from child functions that indicates a specific condition has been met. WordPress uses WP_Error and is_wp_error() for this sort of operation. Any number of nested functions can check to see if a called function returned an error state, and opt to pass that error up the chain rather than continue with processing.
Example:
function outer() {
$result = inner();
// pass failure back to parent
if( is_wp_error($result) ) {
return $result;
}
// other processing
return $final_result;
}
function inner() {
if( some_condition() ) {
// generate an error
return new WP_Error( 'code', 'message' );
}
return $other_result;
}
$result = outer();
// did we get an error?
if( is_wp_error($result) ) {
echo 'Something went wrong.';
} else {
echo $result;
}
Yes, you can very simply construct a "body-less" while() or if() block. Typically, you will see PSR-12 compliant PHP code using {} to bookend the body of the loop/condition block, but the body is not required. Writing a semicolon at the end of the line will be sufficient and your IDE will not complain about bad syntax.
Returning a truthy value from each function will be an adequate indicator that the following function is authorised for execution.
This will provide the "short circuit" functionality that is desired without creating nested control structures or passing variables into different scopes.
I'll demonstrate with a battery of generic functions:
function echo1T() {
echo "1";
return true;
}
function echo2T() {
echo "2";
return true;
}
function echo3T() {
echo "3";
return true;
}
function echo1F() {
echo "1";
return false;
}
function echo2F() {
echo "2";
return false;
}
function echo3F() {
echo "3";
return false;
}
Code: (Demo with more scenarios)
while (echo1T() && echo2F() && echo3T()); // outputs: 12
if (echo1T() && echo2F() && echo3T()); // outputs: 12
$return = echo1T() && echo2F() && echo3T(); // outputs: 12
var_export($return); // outputs false
Is there a way I can have my PHP function return a different value type?
The following code should explain what I mean:
<?php
public function test($value){
if($value == 1){
return "SUCCESS";
} else {
return false;
}
}
?>
On one condition I'm returning a string, otherwise I'm returning a Boolean. Is that allowed/possible?
Yes. PHP is loosely typed, so any variable can take any type. Function return values are no exception.
Yes, it's possible (but not advisable).
You should at least declare it in your Javadoc comment
/**
* #param int $value
* #return mixed string|boolean
**/
public function test($value){
if($value == 1){
return "SUCCESS";
} else {
return false;
}
}
Even PHP's built in functions do it sometimes (e.g mysql_connect => boolean | resource link)
It is allowed. However, it is not advisable in the case you gave. For an example where this makes sense, take a look at e.g. strpos() function.
Yes, that's allowed, not like in C, Java, ..., where you have to define the return.
I wonder about this myself, why return something that is different? So the receiving end gets two things to check?
I think I have settled on returning an empty version of the type or an array with a status element myself.
Two examples, how things can change within a function/method, and you are basically forced to check more than expected:
<?php
function test($value) {
if ($value == 1) {
$local = successFunction($value);
return $local;
}
else {
return false;
}
}
$res = test(1);
if ($res) {
echo "Are we OK? Right? No? What is this?";
}
Version 2
function test($value) {
if ($value == 1) {
$local = successFunction($value);
return $local;
}
else {
return "";
}
}
$res = test(1);
if (!empty($res)) {
echo "More likely we are OK.";
}
?>
Is that allowed/possible?
Yep.