Regarding memory and variable assignment in PHP [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Ive asked a similar question before but i was really unclear so ive decided to use a more concrete example.
Does php save the result of the variable or does it save the procedure to run it? Why im wondering is if i store a function in it, does it store the return value or just copies the procedure
say:
function foo($something)
{
for loop
{
echo 'Something';
}
return $something;
}
$b = foo(5);
from what i encountered just assigning the value executes the function. Which i dont want because i dont want to go through double the for loops and do double what could be inside.

In PHP you can have both (either store result, or function's code)
if you write:
function foo()
{
return 5;
}
$a = foo();
this will mean - execute function foo and store result into $a
if you write:
$a = function()
{
return 5;
};
$a();
this will mean - store function's code into variable $a, then execute function stored in $a

PHP is a strict programming language, meaning that expressions are always completely evaluated. The line
$b = foo(5);
computes the value for foo(5) before the assignment; PHP does not leave it as a thunk to be evaluated when or if the variable $b is used.
If you want to you can achieve something similar to a thunk by creating a closure, like this:
$b = function() { return foo(5); };
This will not evaluate foo(5) until its value is needed, and then to get the value you must call the closure as $b().

Related

Why is PHP typecasting different from another functions? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Functions in PHP are constructed like this foo($bar) with the variable $bar as parameter. When you want to convert the values of the $bar to a boolean or string, you need to do the following:
(string)$bar;
I find it that little bit odd, given the syntax of another functions. Why is Type Casting in PHP performed this way, compared to many other languages, like this:
ToString($bar);
for example. I am seeking to better understand the syntactic design of the language.
(string) is the actual data type internally. So consider this
$bar = 0; //int
$foo = '0'; //string
All the string conversion does is try to make a single string out of the value. In other words, it simply converts numbers into their character counterparts. It doesn't natively work with constructs, like array
$bar = [0];
echo (string)$bar; // E_NOTICE: array to string conversion, outputs 'Array'
Now, along the lines of your question, objects can have a magic method __toString()
class Foo {
protected $bar = 'Hi';
public function __toString() {
return $this->bar;
}
}
$x = new Foo();
echo (string)$x; // outputs 'Hi'
When we try to convert the Foo object to a string it calls the magic method

How to find number of variables passed in function in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to find how to get number of variables to be passed in function.
say suppose I have function
public function abc($id,$name,$email){
....
}
Now there is another function xyz in want to know number of variables that are need to be passed in this function.
Thanks in advance.
Now there is another function xyz in want to know number of variables that are need to be passed in this function.
Use this:
$rfunc = new ReflectionFunction('xyz');
echo $rfunc->getNumberOfRequiredParameters();
But I do not know for what this should be useful...
if you did not know how many number of variables that are need to be passed in calling function, then you can make use default value of parameter concept.
For ex:
// Function call-1
abc($a,$b,$c);
// Function call -2
abc($a,$b,$c,$d);
// Function defination goes here
function abc($a,$b,$c,$d=0)
{
/* if you did not pass $d value , $d gets assigned automatically to 0
as default value. So in this way, you should not be worried about how
many parameters you should pass */
}

Is it normal practice to use variables to store parameter data? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In some examples of PHP, I see people assign things to shorthand variables, and then use the shorthand variables instead. Is this common practice? Is this good practice?
$name = $_POST['name'];
and then they use they use $name down here to echo it or use it as a function parameter.
Another example is:
DEFINE('DB_USER', 'username');
mysqli_connect(DB_USER.......);
Pros:
Shorthand variables can be easier to type and remember.
A shorthand variable might allow an expensive operation to be done once instead of repeated many times. But beware of premature optimization! Most of the time this sort of optimization would be premature.
A shorthand variable can be used to make a copy that can be changed without modifying the original variable.
In some languages, a shorthand variable can be used to make a copy that is guaranteed to persist even if the the original variable is modified.
Cons:
Indiscriminate use of shorthand variables can result in multiple names for the same values.
In some languages and situations, a shorthand variable will make an unnecessary copy, using additional resources.
I have been doing php professionally for about 5 years now.
Usually when getting post variables it is a good idea, but even more common is to wrap it in an isset ternary if statement:
$name = isset($_POST['name']) ? $_POST['name'] : false;
This way if the variable isn't passed then you don't get an undefined variable warning.
Further, it saves you having to type $_POST every time, and it helps encapsulate the code a bit better.
The most important thing when writing code is writing readable code, not just for others but also for yourself. We do this all the time, i.e. abstracting and applying oo methods of programming.
So predefining the variables we'll be using and setting defaults makes perfect sense.
I would do something like this...
class ValueTooLong extends Exception {}
function R($param, $default=null, $type='string', $max_length=null) {
if(!isset($_REQUEST[$param]))
return $default;
$r = $_REQUEST[$param];
if($max_length && strlen($r) > $max_length)
throw new ValueTooLong('Length of '.$param.' was '.strlen($r).'. Max length is: '.$max_length);
if($type === 'bool' || $type === 'boolean') {
if($r === 'false' || $r === 'no')
return false;
return !empty($r);
}
settype($r, $type);
return $r;
}
# Which allows me do do this:
$name = R('name');
# or:
$count = R('count', 1, 'int');
EDIT: Function now takes a max_length parameter (as suggested by comment) and throws an exception if value of request parameter is too long

PHP - same code on one or multiple lines [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This are two lines of codes. Could anyone tell me what the difference is between the first way and the second? I'd like both to do exactly the same thing.
$test = isset($_POST['test'])?$_POST['test']:[];
if(isset($_POST['test'])){
$test[] = $_POST['test'];
}
Thanks !
First one sets $test to an empty array if $_POST['test'] is unset. However, the second one does not set $test to a default value. In fact, if $_POST['test'] was unset, $test would be un-existent/undefined/etc.
You would need to run $test = []; at the beginning of the second one to archive the exact same result.
the top line would be equivalent to
if(isset($_POST['test'])){
$test = $_POST['test'];
}else{
$test = [];
}
The first uses a ternary operator, which is a shorthand for if (X) then $a = b else $a = c, which sets $test to $_POST['test'] if it isn't empty, or $test to an empty array.
The second example doesn't have the else case, so it will leave $test undefined if $_POST['test'] is empty.
See also the ternary operator section of this page in the PHP manual http://www.php.net/manual/en/language.operators.comparison.php.

"Indirect" isset() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
function myCheck($in)
{ return isset($in); }
$var1='Something';
$var2='$var1';
$var3='$varNonExitant';
What I'm trying to achive is to use myCheck to evaluate the existance of the content like this:
myCheck($var2) return true;
myCheck($var3) return false;
isset() is not really a function: it's a language construct. As such, it's allowed to do some magic that's not available to regular functions, such as being fed with non-existing variables.
To sum up: you cannot replicate it with a custom function.
Edit:
As DaveRandom pointed out in a comment below, all you can do is come close by checking if a variable isset for example:
function variable_isset(&$variable = NULL) {
return isset($variable);
}
This approach offers two drawbacks though:
This works by passing the unset variable by reference, thus creating it when called. As it's NULL it is still not set.
It'll trigger an Undefined variable notice if the variable does not exist, ruining the whole concept of gracefully handling optional variables.
Most likely this should not be needed. So question remains why you can not use isset in the first place which would be much more needed to give you better guidance.
When you cyall myCheck($abc), with set $abc = 123, it gets myCheck(123). It isn't any valid argument for isset.
You have to give the function a string with variable name:
function isset_global($variable_name)
{
return isset($GLOBALS[$variable_name]);
}
Of course, I am also wondering, why to do this, but it answers the question as long as you check a global variable.

Categories