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
Related
Can I use a function as the default value of an argument in another function? In the example below, I'm trying to use the Wordpress function get_the_title() as the default value:
function GetPageDepartment($department = get_the_title()) {
return $department;
}
As is, the parentheses are causing a parse error. Is there a way around this, or would I have to pass the function value to a variable somewhere outside of the default values?
I know the actual code here would be largely pointless as it just returns get_the_title(), but it's just as an example, as what I actually do with the argument isn't that relevant to the question.
The answer is "no and yes, but ... yet...".
No, using PHP 5.6 you can't assign a function as a default value of a function/method.
Yes, you can assign a string and if you use that parameter/variable in a function context, i.e. echo $department();, the string will be treated as the name of a function and get_the_title() will be invoked. But... it's kinda ugly that you have to rely on the string->function name relation. Yet ... who cares?
edit: for your consideration....
<?php
function get_the_title() { return "the title"; }
function GetPageDepartment( callable $department=null ) {
if ( null==$department ) {
$department = 'get_the_title';
}
return '<'.$department().'>';
}
echo GetPageDepartment();
No you can't
use this code
<?php
function get_the_title(){
return 'this is the title';
}
$temp = get_the_title();
function GetPageDepartment($department) {
echo $department;
}
GetPageDepartment($temp);
In the end, I plumped for:
function GetPageDepartment($department = null) {
$department = $department ?: get_the_title(); //Sets value if null.
}
which sets the value of $department to get_the_title() if no other value's set.
How would I alter the function below to produce a new variable for use outside of the function?
PHP Function
function sizeShown ($size)
{
// *** Continental Adult Sizes ***
if (strpos($size, 'continental-')!== false)
{
$size = preg_replace("/\D+/", '', $size);
$searchsize = 'quantity_c_size_' . $size;
}
return $searchsize;
Example
<?php
sizeShown($size);
$searchsize;
?>
This currently produces a null value and Notice: undefined variable.
So the function takes one argument, a variable containing a string relating to size. It checks the variable for the string 'continental-', if found it trims the string of everything except the numbers. A new variable $searchsize is created which appends 'quantity_c_size_' to the value stored in $size.
So the result would be like so ... quantity_c_size_45
I want to be able to call $searchsize outside of the function within the same script.
Can anybody provide a solution?
Thanks.
Try using the global keyword, like so:
function test () {
global $test_var;
$test_var = 'Hello World!';
}
test();
echo $test_var;
However, this is usually not a good coding practice. So I would suggest the following:
function test () {
return 'Hello World!';
}
$test_var = test();
echo $test_var;
In the function 'sizeShown' you are just returning the function. You forgot to echo the function when you call your function.
echo sizeShown($size);
echo $searchsize;
?>
But the way you call $searchsize is not possible.
This is an old question, and I might not be understanding the OP's question properly, but why couldn't you just do this:
<?php
$searchsize = sizeShown($size);
?>
You're already returning $searchsize from the sizeShown method. So if you simply assign the result of the function to the $sizeShown variable, you should have what you want.
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
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 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.