I'm trying to pass a variable into an operator instead of having it be fixed
$client ->setDeveloperKey('a very long hexadecimal string');
This is how the script is written to work and it works - some value is a very long hex code...
The script I'm writing takes the developer key from an input i.e. $value='some value' is already defined BEFORE the statement.
Instead of being fixed, I'd like to assign $value into the setDeveloperKey operator - its coming in as a function i.e.
callGoogle ($query,$devkey)
where callGoogle is the function. However when I try
$client ->setDeveloperKey($devkey);
the script doesn't work...in other words its the wrong syntax to assign my developer key (string) to the operator.
Nor does
$client ->setDeveloperKey = $devkey;
What is the correct PHP syntax to assign the $value variable to the $client - > setDeveloperKey operator?
First check the type of your $value and also check if that class method accept that value type. From what I can see its a Google_Client API and that method accepts Strings
If this works:
$obj->method('test');
Then this works too:
$value = 'test';
$obj->method($value);
You must be messing somewhere else.
Well what type of object is $client? You have to define your own class, and create a function called setDeveloperKey, or this is a pre existing class / function, the syntax would be $client->setDeveloperKey('foo');
The original class should look something like this:
class Client {
protected $DeveloperKey;
public function setDeveloperKey($Key) {
$this->DeveloperKey = $Key;
}
}
Related
Hello I'm writing an article allowing to bypass a filter that allows only base_convert except that there is something I discovered recently is that when we write this syntax in php:
"system"("id")
the function is interpreted, do you have a technical explanation for this?
Thanks to you !
Functions in PHP aren't first-class objects. What does that mean? When you want to pass around a function, for example as callback to array_map, you cannot just pass the function itself like so:
function my_callback() { ... }
array_map(my_callback, $some_array)
my_callback here is interpreted as a constant, and barring its existence, a bare string. (This works in other languages where functions are first class objects.) You can only pass the function by name, which means you pass a string that contains the name of the function:
array_map('my_callback', $some_array)
PHP will then look up the globally registered function with the name "my_callback" and use it.
This means inside array_map it must look something like this:
function array_map($callback, $array) {
$callback($array); // let's ignore the "mapping" part…
}
So, a variable can hold the name of a function, and "calling" that variable which holds the name of a function actually calls that function.
Now, we know that a variable can just as well be replaced with a literal of the same value:
$a = 1;
$b = 2;
$c = $a + $b;
is the same as:
$c = 1 + 2;
The same happens to hold for calling-strings-with-names-of-functions:
'my_callback'($array)
Note that this only works since PHP 7, where the PHP parser got a huge revamping. Before, $f() was sort of a special case hack, but the PHP 7+ parser properly follows the variable-is-substitutable-by-literal logic.
How to call something like this:
$instance = new ($b->method($id))();
where method(int $id): string returns class name?
The construct above gives me a syntax error, but this is ok:
$className = $b->method($id);
$instance = new $className();
I'm just wondering if and how it can be done.
I was surprised that brackets could not say that content of brackets $b->method($id) should be executed first and resulting string used to object instantiating.
I probably will not use it in production code, but I'm still interested.
This is not possible on PHP because 'new' needs a string or variable with a string.
The () characters are used for aritmethic associations and for parameters on languaje constructions, and you can't assign to new the result of a call to another function.
I need to use variable function names for a project I'm working on but have run into a bit of strange issue. The function name ends up as a string element in an array.
This works:
$func = $request[2];
$pages->$func();
This doesn't:
$pages->$request[2]();
And I can't figure out why. It throws an array to string conversion error, as if it's ignoring that I have supplied a key to a specific element. Is this just how it works or am I doing something wrong?
As for php 5, you can use curly-braced syntax:
$pages->{$request[2]}();
Simple enough example to reproduce:
<?php
$request = [
2 => 'test'
];
class Pages
{
function test()
{
return 1;
}
}
$pages = new Pages();
echo $pages->{$request[2]}();
Alternatively (as you noted in the question):
$methodName = $request[2];
$pages->$methodName();
Quote from php.net for php 7 case:
Indirect access to variables, properties, and methods will now be
evaluated strictly in left-to-right order, as opposed to the previous
mix of special cases.
Also there is a table for php 5 and php 7 differences for this matter just below quote in the docs I've supplied here.
Which things you should consider:
Check value of the $request[2] (is it really a string?).
Check your version of php (is it php 5+ or php 7+?).
Check manual on variable functions for your release.
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.