I hope this question is not too simple, but I have no idea how to do this
$book = 'book';
$car = 'car';
function $book()
{
return "Hello, world!";
}
function $car()
{
return "WoW , The red car";
}
You cant do that, you have 2 options.
A couple of ways:
Use variable functions:
<?php
$book = 'book';
$car = 'car';
function book()
{
return "Hello, world!";
}
function car()
{
return "WoW , The red car";
}
echo $book();
echo $car();
Or closures:
<?php
$book = function () {
return "Hello, world!";
};
$car = function() {
return "WoW , The red car";
};
echo $book();
echo $car();
You can write an anonymous function:
$book = function() {
return "Hello, world!";
};
echo $book(); // invoke it
Class
class foo
{
public function __invoke(){ echo "hello"; }
}
Test
$obj = new foo;
$obj();
Output
hello
Online Sandbox
You can also use reflection (to call an existing function as a string)
(new ReflectionFunction('print_r'))->invoke("hello");
Outputs
hello
ReflectionMethod is nice too, because it maintains state of the object, for example
class foo{
protected $bar;
public function setBar($bar){ $this->bar = $bar;}
public function bar(){ echo $this->bar; }
}
$obj = new foo;
$obj->setBar("good bye");
(new ReflectionMethod($obj, 'bar'))->invoke($obj);
Outputs
good bye
You can call a function with variable name like this:
Variable functions
<?php
$a = 'book';
function book() {
echo 'book function';
}
// this is equivalent to book()
$a();
So to expand a little bit:
<?php
$functions = ['book', 'car'];
function book() {
return "Hello, world!";
}
function car() {
return "WoW , The red car";
}
foreach ($functions as $function) {
echo $function() .'<br>';
}
The OUTPUT would be:
Hello, world!
WoW , The red car
Another way of doing it to get same output:
Anonymous functions
$book = function() {
echo 'book function';
};
$book();
In this case, the above function doesn't have an actual name and is represented by a variable.
And let me give you an example:
<?php
$book = function() {
echo 'book function';
};
$a = $book;
echo $a();
So, to expand in the same manner:
<?php
$functions = ['book', 'car'];
$book = function () {
return "Hello, world!";
};
$car = function() {
return "WoW , The red car";
};
foreach ($functions as $function) {
echo ${$function}(). '<br>';
}
DEMO:
http://sandbox.onlinephpfunctions.com/code/1972f1acd72984d459efbfb308680aaa9d7a1fad
Related
Are there any actual difference between the two ways to get the value by reference?
Way 1
<?php
class foo {
public $value = 42;
public function &getValue() {
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->getValue();
// $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;
// prints the new value of $obj->value, i.e. 2.
?>
Way 2
<?php
class foo {
public $value = 42;
public function getValue() {
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->value;
$obj->value = 2;
echo $myValue;
?>
In both cases 2 is printed. So why does one need the getValue() function then? The first example is taken from the PHP Manual.
You need the first approach if class fields don't have a modifier 'public'. In this case you can't get a reference to the field outside the class. See example:
<?php
class foo
{
protected $value = 1;
public function setValue($value)
{
$this->value = $value;
}
public function &getValue()
{
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->getValue();
$obj->setValue(2);
echo $myValue;
?>
How do I make chained objects in PHP5 classes? Examples:
$myclass->foo->bar->baz();
$this->foo->bar->baz();
Not: $myclass->foo()->bar()->baz();
See also:http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
actually this questions is ambiguous.... for me this #Geo's answer is right one.
What you (#Anti) says could be composition
This is my example for this:
<?php
class Greeting {
private $what;
private $who;
public function say($what) {
$this->what = $what;
return $this;
}
public function to($who) {
$this->who = $who;
return $this;
}
public function __toString() {
return sprintf("%s %s\n", $this->what, $this->who);
}
}
$greeting = new Greeting();
echo $greeting->say('hola')->to('gabriel'); // will print: hola gabriel
?>
As long as your $myclass has a member/property that is an instance itself it will work just like that.
class foo {
public $bar;
}
class bar {
public function hello() {
return "hello world";
}
}
$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();
In order to chain function calls like that, usually you return self ( or this ) from the function.
Here's a little mock-up to describe my predicament:
<?php
$var = "Before";
function getVar(){
global $var;
return $var;
}
$array = Array(
"variable" => "Var = " . getVar()
);
$var = "After";
echo $array['variable'];
?>
That code would echo 'Before', I'm aiming for it to echo 'after'. I realize that this is how PHP is supposed to work however it's crucial for the array to execute getVar() only when it's called.
How would I go about doing this?
You can not do this since array declaration will initialize it - so you're mixing function calling at array's 'usage' and at it's definition. There's no 'usage': array is already defined to that moment.
However, an answer could be using ArrayAccess, like this:
class XArray implements ArrayAccess
{
private $storage = [];
public function __construct()
{
$this->storage = func_get_args();
}
public function offsetSet($offset, $value)
{
if(is_null($offset))
{
$this->storage[] = $value;
}
else
{
$this->storage[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset($this->storage[$offset]);
}
public function offsetUnset($offset)
{
unset($this->storage[$offset]);
}
public function offsetGet($offset)
{
if(!isset($this->storage[$offset]))
{
return null;
}
return is_callable($this->storage[$offset])?
call_user_func($this->storage[$offset]):
$this->storage[$offset];
}
}
function getVar()
{
global $var;
return $var;
}
$var = 'Before Init';
$array = new XArray('foo', 'getVar', 'bar');
$var = 'After Init';
var_dump($array[1]);//'After Init'
-i.e. try to call data, which is inside element, when actual get happened. You may want to have different constructor (for associative arrays) - but the general idea was shown.
Editing my answer after the question was edited.
No, what you are trying to achieve isn't possible because when you call the function it returns and it's done at that point. But you could achieve something similar with object oriented coding. I'll create something for you, please wait.
<?php
class Foo {
public function __toString() {
global $var;
return "Var = {$var}";
}
}
$var = "Before";
$array = array( "variable" => new Foo() );
$var = "After";
echo $array['variable'];
?>
PS: Sorry for the late answer, but there was a blackout in Salzburg. :(
It occurred to me that you could also use anonymous functions and invoke/execute those
Proof of concept:
$var = "Before";
function getVar(){
global $var;
return $var;
}
$array = Array(
"variable" => create_function(null, "return 'Var = ' . getVar();")
);
$var = "After";
echo $array['variable']();
returns
Var = After
I want to have a function and then use it multiple times with different parameters.
For example:
<?php
class Test {
var $test;
public function func($val) {
$this->test = $val;
}
public function buildFunc() {
if(!empty($this->test)) {
$ret = $this->test;
}
return $ret;
}
}
?>
Then on calling page:
$test = new Test;
$test->func("test1");
$test->func("test2");
echo $test->buildFunc();
Then it prints test2 on the screen. And I want it to print out both of them.
Either create 2 instances of your object;
$test1 = new Test;
$test1->func("test1");
$test2 = new Test;
$test2->func("test2");
echo $test1->buildFunc();
echo $test2->buildFunc();
Or make test an array;
class Test {
var $test = array();
public function func($val) {
$this->test[] = $val;
}
public function buildFunc() {
return print_r($this->test, true);
}
}
May be you mean that you want to store all values? Then use an array:
public function func($val) {
$this->test[] = $val;
}
public function buildFunc() {
return $this->test
}
And then work with the result as with an array.
Well.. your code does exactly what are you telling it to do. Consider situation when you have no OOP:
$str = 'test 1';
$str = 'test 2';
echo $str; //prints test 2
So you need to echo them separately as if it wont be an OOP situation.
$test = new Test;
$test->func("test1");
echo $test->buildFunc();
$test->func("test2");
echo $test->buildFunc();
When calling the method create 2 instances of the test object.
$test = new Test;
$test->func("test1");
echo $test->buildFunc();
$test2 = new Test;
$test2->func("test2");
echo $test2->buildFunc();
if you dont want to create 2 instances you have to make a array instead.
How about create a constructor and initialize the value of test and concat the second value.
<?php
class Test {
var $test;
public function __construct($init){
$this->test = $init;
}
public function func($val) {
$this->test .= $val;
return $this;
}
public function buildFunc() {
if(!empty($this->test)) {
$ret = $this->test;
}
return $ret;
}
}
$test = new Test("test1");
$test->func("test2");
echo $test->buildFunc();
?>
When you say both do you mean something like
test1test2
or do you want
test1
test2
For the first option you can just append the string:
<?php
class Test {
var $test;
public function func($val) {
$this->test = $test . $val; <-- add val to the end
}
public function buildFunc() {
if(!empty($this->test)) {
$ret = $this->test;
}
return $ret;
}
}
?>
For the second:
<?php
class Test {
var $test = array();
public function func($val) {
$this->test[] = $val; <-- add val to
}
public function buildFunc() {
if(!empty($this->test)) {
foreach($test as $item){
echo $item . "<br/>";
}
}
}
}
?>
Push the variables to an array
<?php
class Test {
var $test;
public function __construct(){
$this->test=array();//Declare $test as an array
}
public function func($val) {
$this->test[]=$val;//Push to array
}
public function buildFunc() {
if(!empty($this->test)) {
$ret = implode(",",$this->test);
}
return $ret;
}
}
?>
function nothing() {
echo $variableThatIWant;
}
You can put "global" before the variable you want to use, Like this :
<?php
$txt = "Hello";
function Test() {
global $txt;
echo $txt;
}
Test();
?>
OR :
you can passed it as parameter, Like this :
<?php
$txt = "Hello";
function Test($txt) {
echo $txt;
}
Test($txt);
?>
source : http://browse-tutorials.com/tutorial/php-global-variables
The better way is to pass it as an argument.
function nothing($var) {
echo $var;
}
$foo = 'foo';
nothing($foo);
The evil way, and I dont know why I'm even showing you this, is to use global.
function nothing() {
global $foo;
echo $foo;
}
$foo = 'foo';
nothing();
You have to use global.
$var = 'hello';
function myprint()
{
global $var;
echo $var;
}
You can also use a class property (or member variable) if you are inside a class:
<?php
$myClass = new MyClass();
echo $myClass->nothing();
class MyClass {
var $variableThatIWant = "something that I want";
function nothing() {
echo $this->variableThatIWant;
}
}
Codepad example
You can pass it by reference if you want to modify it inside the function without having to return it:
$a = "hello";
myFunction($a);
$a .= " !!";
echo $a; // will print : hello world !!
function myFunction(&$a) {
$a .= " world";
}
Codepad example