PHP newbie question: return variable with function? - php

i've been coding asp and was wondering if this is possible in php:
$data = getData($isEOF);
function getData($isEOF=false)
{
// fetching data
$isEOF = true;
return $data;
}
the function getData will return some data, but i'd like to know - is it possible to also set the $isEOF variable inside the function so that it can be accessed from outside the function?
thanks

It is possible, if your function expects it to be passed by reference :
function getData(& $isEOF=false) {
}
Note the & before the variable's name, in the parameters list of the function.
For more informations, here's the relevant section of the PHP manual : Making arguments be passed by reference
And, for a quick demonstration, consider the following portion of code :
$value = 'hello';
echo "Initial value : $value<br />";
test($value);
echo "New value : $value<br />";
function test(& $param) {
$param = 'plop';
}
Which will display the following result :
Initial value : hello
New value : plop

Using the global statement you can use variables in any scope.
$data = getData();
function getData()
{
global $isEOF;
// fetching data
$isEOF = true;
return $data;
}
See http://php.net/manual/en/language.variables.scope.php for more info.

Yes, you need to pass the variable by reference.
See the example here : http://www.phpbuilder.com/manual/functions.arguments.php

Related

Returning Multiple Variables with isset()

I have a bit of code that returns the user agent, running it through a function to parse it. The code I have previously used returns only one variable from the parsing function (there are three: 'platform' 'browser' 'version'):
function my_get_user_agent($value)
{
$browser = parse_user_agent();
return isset($browser['platform']) ? $browser['platform'] : '';
}
While this code works to return the platform of the user agent, I need to append it to return all three variables in the function. I changed the first half of the code to what I assume is correct:
return isset($browser['platform'], $browser['browser'], $browser['version'])? $browser['platform'] : '';
I am unsure, however, as to what I need to do to properly return all three values. Suggestions?
You can just return the entire array:
return $browser;
Then access the values later:
$browser['platform'];
$browser['browser'];
$browser['version'];
Reading your question again, you seem to want to ensure the value are set. You can do this:
foreach($browser as $value) {
if(isset($value)) {
$data[] = $value;
}
}
return $data;
Now data will contain platform, browser, and version.
There is no tuple structure in PHP: Are there tuples in PHP?
You can either return the whole browser array, or a subset like this (this will not return the undefined values):
array_intersect_key($browser, array_flip(array("platform", "browser", "version")))
Also, if you want to set the result of your function to variables, the list construct can be handy, but you have to be sure that the values are in that order and that they exist. For that you would have to proceed like SeanWM suggested:
function my_get_user_agent($agent) {
$browser = parse_user_agent($agent);
foreach(array("platform", "browser", "version") as $value) {
$data[] = isset($browser[$value]) ? $browser[$value] : '';
}
return $data;
}
list($platform, $browser, $version) = my_get_user_agent($agent);

array_search wrong argument datatype

I am playing around with this:
$sort = array('t1','t2');
function test($e){
echo array_search($e,$sort);
}
test('t1');
and get this error:
Warning: array_search(): Wrong datatype for second argument on line 4
if I call it without function like this, I got the result 0;
echo array_search('t1',$sort);
What goes wrong here?? thanks for help.
Variables in PHP have function scope. The variable $sort is not available in your function test, because you have not passed it in. You'll have to pass it into the function as a parameter as well, or define it inside the function.
You can also use the global keyword, but it is really not recommended. Pass data explictly.
You must pass the array as a parameter! Because the functions variables are different from globals in php!
Here is the fixed one:
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t2',$sort);
You cannot directly access global variables from inside functions.
You have three options:
function test($e) {
global $sort;
echo array_search($e, $sort);
}
function test($e) {
echo array_search($e, $GLOBALS['sort']);
}
function test($e, $sort) {
echo array_search($e, $sort);
} // call with test('t1', $sort);
take the $sort inside the function or pass $sort as parameter to function test()..
For e.g.
function test($e){
$sort = array('t1','t2');
echo array_search($e,$sort);
}
test('t1');
----- OR -----
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t1',$sort);

how to extract value from variable in PHP function?

This is probably a silly question but how do you extract the value of a variable inside a PHP function? I found this code on stackoverflow on how to find the title of the webpage:
function page_title($url)
{
$fp = file_get_contents($url);
if (!$fp)
return null;
$res = preg_match("/<title>(.*)<\/title>/", $fp, $title_matches);
if (!$res)
return null;
$title = $title_matches[1];
return $title;
}
I have a variable called $extract outside the function above and want to insert the value of $title from the function into the outside variable, $extract. I'm assuming you have to call the function first and then do something else to achieve this but I don't know what that step is.
If I call the function and the variable $title returns the value "welcome to my website", I want to associate that value with the outside variable, $extract.
$extract = page_title($url);
place that outside the function and you should be good to go
You can simply assign the value returned by a function to your property:
$value = somefunc();
echo $value;
function somefunc()
{
return "trendy value";
}
just write
$extract = page_title($url);
Outside your function. i.e. make function call like the above line and returned value whther null or $title will be stored to extract

PHP and DRUPAL, Cannot save values in a static variable and pass through function

Developing a module for drupal and I need to pass/modify variables within functions. I avoided using global variables because drupal uses the include function which subsequently makes my global variable into local.
As such, i created the following script which stores a static variable but I cannot retain the new value. Any help will be appreciated
function _example_set_flashurl($value = '21224', $clear = NULL) {
static $url;
if ($clear) {
// reset url variable back to default
$url = null;
}
// assigned url a perminate value within this function
$url = $value;
return $url;
}
function _example_get_flashurl() {
return _example_set_flashurl();
// retrieve the value inside set scope
}
_example_set_flashurl('another', TRUE);
print _example_get_flashurl(); // prints 21224, I want it to print another
Try this
<?
function _example_set_flashurl($value = '21224', $clear = NULL) {
static $url;
if ($clear) {
// reset url variable back to default
$url = null;
}
if($value!='21224') {
// assigned url a perminate value within this function
$url = $value;
}
return $url;
}
function _example_get_flashurl() {
return _example_set_flashurl();
// retrieve the value inside set scope
}
_example_set_flashurl('another', TRUE);
print _example_get_flashurl(); // prints 21224, I want it to print another
You override the value in the empty call to set in your get function.
First, you probably want to add the default value directly to the static and not the argument. Like this: "static $url = '21224';". Then, this value will also be returned when set has never been called.
Second, there is no need for a $clear argument if you can pass in any value you want. If you want to change it, just override the old value.
Third, as the answer from bruce dou showed, you want to protect it against accidently overriding the value.
So, this code for the set function should be all you need:
<?php
function _example_set_flashurl($value = FALSE) {
static $url = '21224';
// Only keep value if it's not FALSE.
if ($value !== FALSE) {
// assigned url a perminate value within this function
$url = $value;
}
return $url;
}
?>

What does & before the function name signify?

What does the & before the function name signify?
Does that mean that the $result is returned by reference rather than by value?
If yes then is it correct? As I remember you cannot return a reference to a local variable as it vanishes once the function exits.
function &query($sql) {
// ...
$result = mysql_query($sql);
return $result;
}
Also where does such a syntax get used in practice ?
Does that mean that the $result is returned by reference rather than by value?
Yes.
Also where does such a syntax get used in practice ?
This is more prevalent in PHP 4 scripts where objects were passed around by value by default.
To answer the second part of your question, here a place there I had to use it: Magic getters!
class FooBar {
private $properties = array();
public function &__get($name) {
return $this->properties[$name];
}
public function __set($name, $value) {
$this->properties[$name] = $value;
}
}
If I hadn't used & there, this wouldn't be possible:
$foobar = new FooBar;
$foobar->subArray = array();
$foobar->subArray['FooBar'] = 'Hallo World!';
Instead PHP would thrown an error saying something like 'cannot indirectly modify overloaded property'.
Okay, this is probably only a hack to get round some maldesign in PHP, but it's still useful.
But honestly, I can't think right now of another example. But I bet there are some rare use cases...
Does that mean that the $result is returned by reference rather than by value?
No. The difference is that it can be returned by reference. For instance:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = a($c);
$d++;
echo $c; //echoes 1, not 2!
To return by reference you'd have to do:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = &a($c);
$d++;
echo $c; //echoes 2
Also where does such a syntax get used in practice ?
In practice, you use whenever you want the caller of your function to manipulate data that is owned by the callee without telling him. This is rarely used because it's a violation of encapsulation – you could set the returned reference to any value you want; the callee won't be able to validate it.
nikic gives a great example of when this is used in practice.
<?php
// You may have wondered how a PHP function defined as below behaves:
function &config_byref()
{
static $var = "hello";
return $var;
}
// the value we get is "hello"
$byref_initial = config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
// However, let’s make a small change:
// We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
// the value we get is "hello"
$byref_initial = &config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
// If you define the function without the ampersand, like follows:
// function config_byref()
// {
// static $var = "hello";
// return $var;
// }
// Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.

Categories