I don't understand this code:
$outputFunction($dst, $resized, $quality);
It's not a function e.g myfunction()
It's not a variable e.g $variable = $variable2
What is it?
The code works in the script i have downloaded, i just can't figure out how that piece of code can work...maybe i'm just tired or something..
Thanks.
$outputFunction holds the name of the function. Thus, if $outputFunction holds the value "calculate", then calculate($dst, $resized, $quality) is invoked.
To add to sbrattla's answer, you can also define anonymous functions in PHP 5.3 (I think), so
$var = function($a) { /* do something */ return $b; }
echo $var(123);
These are variable functions.
$outputFunction is evaluated to obtain the name of the function to which the operands will be applied.
There's an entire page dedicated to this topic in the PHP manual.
in php you can do something like
$outputFunction = 'myFunction';
$outputFunction(args);
and it works calling the function normally
variable functions
The string should initialized some lines before. You can consider this as a pointer of funcrion which allows to change the executed method.
Php will recognize your syntax and will launch the function named in your string (computed one if you want)
Related
EDIT*** my question was a bit hard to understand...let me try again.
I'm having a problem understanding variables and the way they execute their value.
for example.
if I say
$var name= 'mike';
then if I test the page nothing will show because nothing on the HTML is requesting the value of mike.
if I did
echo $name;
then the page would simply show mike.....
that said, if i now do this:
$connect2db = mysqli_connect('values here');
if(!$connect2db){
die("error connecting to the database" . mysqli_error);}
$db_query = mysqli_query($connect2db, "INSERT INTO email_list(email, firstname, lastname)
VALUES ('$email', '$fname', '$lname')");
for inserting these values from a form to the db,
I don't understand how the connection and the commands to the db are being called and put into play because to me
$connect2db equals to "those commands" but nothing is calling it. all $connect2db equals to literally is the instruction to take once its called into play.
where on this chunk of code is the connection being called/put into play? where on this code block is the code being called into action(like the echo above calls $name to be put into action to display its value"???.
I don't see anything on that connect2db variable that calls its action/connection properties to work.
like for example if I was to say
pseudo
if(is true){
this.$db_query;
}
this I understand, this to me means that IF something evaluates to true, do the thing in the middle..
with the original first code block, its like the variable is naming and calling itself at the same time.
In reference to
$connect2db = mysqli_connect('values here');
you mention:
$connect2db equals to "those commands" but nothing is calling it. all
$connect2db equals to literally is the instruction to take once its
called into play.
That is not true. mysqli_connect is a function, and using that syntax (functionname(argument)) actually calls that function. What $connect2db is used for is to store the return value from that function.
To sum up what goes on on that line:
a call to an existing function called mysqli_connect is made. This
executes the function.
the return value from that function gets stored in a variable named $connect2db
The rules governing this assignment are defined by operator precedence, which in this case specifies that the function call will be evaluated prior to the assignment.
To know what the type of return that is, one must look at the API documentation for this function, and in this case it is an object (which represents the connection to the server).
Now it is possible to have a variable contain a function, like what you thought your example meant. The syntax of this - called an anonymous function, would be like so:
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
You can see that instead of the format:
functionname + parenthesis + argument(s) + parenthesis + semicolon
the format is:
function + parenthesis + argument(s) + parenthesis + open bracket
+ function definition + close bracket + semicolon
In this case, the variable holds what the function does, the function has not beem executed, and to execute it you would use the first format:
$greet('World');
Note that this format is available in PHP 5.3 only, prior to that one needed to use create_function.
Relevant links:
Variables
Functions
Anonymous functions
create_function
Operator precedence
$connect2db contains a resource which describes an active connection. mysqli_query() expects a resource as first parameter, because it needs to know which connection it should use to do what it does. The "action" starts mainly because you called the function and told it what values to use for its job.
I'll think its realy hear to understand your Question :)
So I try my best :)
If you would print 'Mike' via $name you have to register the Variable
<?php
$name = 'Mike';
echo $name;
?>
This even works in Classes
<?php
class Names {
/* Set the default to Mike */
var $name = 'Mike';
/* Get the Name */
public function getName() {
echo $this->name;
}
/* Override the Name */
public function setName($name = NULL) {
if($name != NULL) {
$this->name = $name;
}
}
}
?>
For building Connections to Databases I suggest to read http://php.net/manual/en/mysqli.query.php there are some realy usefull Scripts
Greets
func(CONST_A) should return 'CONST_A', func($name) should return $name
How to implement this func in PHP?
This doesn't seem possible easily.
You can use reflection to determine the parameters of the function, but that returns the variable names that the function expects, and if you're already inside the function, you kind of already know those.
debug_backtrace is the usual way of peeking at what called you, but it returns the values of the passed arguments, not the variable names or constants that the caller used when making the call.
However, what it does give you is the file name and line number of the caller, so you could open up the file and seek to that line and parse it out, but that would be very silly and you should not do this. I am not going to give you example code for this, as it is so utterly silly that you should not consider doing it ever.
The get_defined_vars thing is a hack and is not guaranteed to work either, and definitely won't work for constants, as get_defined_constants does that.
Try this:
<?php
function getVarConst($var)
{
if (isset($GLOBALS[$var]) // check if there is a variable by the name of $var
{
return $GLOBALS[$var]; // return the variable, as it exists
}
else if (defined($var)) // the variable didn't exist, check if there's a constant called $var
{
return constant($var); // return the constant, as it exists
}
else
{
return false; // return false, as neither a constant nor a variable by the name of $var exists
}
}
?>
This isn't possible.
You literally want the following right?
define('CONST_A', 'THIS COULD BE ANYTHING');
$name = 'who cares';
func(CONST_A); //returns 'CONST_A'
func($name); //returns '$name'
The function can't know that.
I suppose that reading the source code like Charles describes could get you this, but why?
Sorry for such a lame title, but I just had no idea what to put there, hope you understand it. Plus, I have no idea if similar question has been asked before, because I don't know the proper keywords for it - therefore couldn't google it too.
Basicly... When looking at preg_match_all();, they got this matches parameter that will create new array defined in function, and give us the ability to access it after function execution.
And the question is.. How can I implement such a feature in my own function? But that it could create single variable and/or array.
Thanks in advance!
preg_match_all() accepts a reference to an array, which in its own scope is called $matches. As seen in the function prototype:
array &$matches
If you call the function and pass in a variable, if it does not already exist in the calling scope it will be created. So in your user-defined function, you accept a parameter by reference using &, then work with it inside your function. Create your outer-scope variable by simply declaring it in your function call, like you the way you call preg_match_all() with $matches.
An example:
function foo(&$bar) {
$bar = 'baz';
}
// Declare a variable and pass it to foo()
foo($variable);
echo $variable; // baz
I think you are referring to function parameters passed by reference, are you not?
function putValInVar(&$myVar, $myVal){
$myVar = $myVal;
}
$myVar = 1;
putValInVar($myVar, 2);
echo $myVar; // outputs '2', but will output '1' if we remove the '&' //
By default function arguments in PHP are passed by value. This means that new variables are created at each function call and those variables will exist only inside the function, not affecting anything outside it.
To specify that an argument should be used by reference the syntax is to append an & before declaring it in the function header. This will instruct PHP to use the passed variable inside the function rather than creating a copy of it.
Exception: Objects are always passed by reference. (Well... Not really, but it's complicated. See the comment thread for more info.)
I think what you are asking for is passing-by-reference. What preg_match_all basically does to "create" an array variable outside its scope is:
function preg_match_all($foo, $bar, & $new_var) {
$new_var = array(1,2,3);
}
The crucial point here is & in the function definition. This allows you to overwrite variables in the outer scope when passed.
Stylistically this should be used with care. Try to return arrays or results instead of doing it via reference passing.
Like this:
$myvariable = runfunction();
function runfunction() {
//do some code assign result to variable (ie $result)
return $result;
}
Or
global $result;
function runfunction() {
global $result;
$result = 'something';
}
I probably should have, but I've never seen this before. Ran into it when looking over the documenation of a Smarty Plugin.
$smarty =& new Smarty;
The =& sign in particular. If you enter it in Google, it gets ignored, just like any other search engine. What is this used for?
Same goes for this function signature:
function connect(&$smarty, $reset = false)
Why the & symbol?
Actually, this code is written to be compatible with PHP 4. The ampersand is useless in PHP 5 (as Tim said - since PHP 5, all objects are passed by reference).
With PHP 4, all variables were passed by value.
If you wanted to pass it by reference, you had to declare a reference assignment :
$ref_on_my_object =& new MyObject();
This code is still accepted with PHP 5 default configuration, but it's better to write :
$ref_on_my_object = new MyObject(); // Reference assignment is implicit
For your second problem, the issue is "almost" the same...
Because PHP lets you declare function arguments (resp. types), and you can't do it for return values.
An accepted, but "not so good" practice is to avoid reference declaration within the function's declaration :
function foo($my_arg) {
// Some processing
}
and to call with a reference...
$my_var;
$result = foo( &$my_var );
// $my_var may have changed because you sent the reference to the function
The ideal declaration would be more like :
function foo( & $my_input_arg ) {
// Some processing
}
then, the call looses the ampersand :
$my_var;
$result = foo( $my_var );
// $my_var may have changed because you sent the reference to the function
It is used for passing values by reference rather than by value which is default in php.
& passes an argument by reference. In this fashion, connect() can manipulate the $smarty object so that the calling function can retrieve the modified object.
Similarly, =& sets a variable by reference.
As Tim said its a reference to a variable. But if you're using a recent version of PHP then all class object are passed by reference anyway. You would still need this if you were passing about arrays, or other builtin types though.
The first example is returning reference, the second is passing reference.
You can read all about it in the PHP manual
& is PHP's reference operator. It's used to return a reference to the object. In this case "new Smarty".
The ampersand will assign a reference to the variable, rather than the value of the object.
One of the primary uses of the ampersand operator is to pass by memory address. This is usually something you do when you want to have a variable changed, but not be returned.
function test_array(&$arr)
{
$varr[] = "test2";
}
$var = array('test');
test_array($var);
print_r($var);
this should output
array( test , test2 );
The purpose of this is usually when you need to pass the actual copy[memory address] you are working with into another function / object. Typically it was used in the past to alleviate a lack of memory and speed up performance, it's a feature from C / C++ and a few other low level languages.
Just a quick and no doubt easy question. I'm pretty new to PHP and am looking through some existing code. I have tried to find the answer to my question on google, but to no avail.
Can somebody please let me know what the '&' sign before the parameter $var does??
function setdefault(&$var, $default="")
{
if (! isset($var))
{
$var = $default;
}
}
Passes it by reference.
Huh?
Passing by reference means that you pass the address of the variable instead of the value. Basically you're making a pointer to the variable.
http://us.php.net/language.references.pass
It means that the function gets the reference to the original value of the argument $var, instead of a copy of the value.
Example:
function add(&$num) { $num++; }
$number = 0;
add($number);
echo $number; // this outputs "1"
If add() would not have the ampersand-sign in the function signature, the echo would output "0", because the original value was never changed.
This means that you are passing a variable by reference http://ca3.php.net/language.references.pass. Simply this means the function is getting an the actual variable and not a copy of the variable. Any changes you make to that variable in the function will be mirrored in the caller.
It’s indicating that the parameter is passed by reference instead of by value.
& means pass-by-reference; what that code does is check whether the variable passed to the function actually exists in the global scope. Without the & it'd try to take a copy of the variable first, which causes an error if it doesn't exist.