PHP Method Check if used for assignment - php

I am not sure if this is possible, however, can we build a method that returns or echo the result based on calling the method directly or used in assignment
function foo()
{
return "bar";
}
$abc = foo();
// $abc will have the value "bar"
But if foo() is called directly, it should echo "bar"
foo();
// should echo / print "bar"
adding echo before foo() solves the problem, but how could this be achieved without using echo. Probably adding some line of code to the function foo()

There is a possible way is to echo inside your function .
Just like
<?php function foo()
{
echo "bar";
return "bar";
}
echo $abc = foo();
?>

Related

Var_dump with echo output

When using var_dump with a function that have an echo like :
<?php
function foo()
{
echo 'Hello';
}
var_dump (foo());
?>
the output is:
HelloNULL
I want to know where the NULL came from
You must set the return the value of the function.
function foo()
{
return 'Hello';
}
var_dump (foo());
Then if you want to retrieve the value of the function just do:
echo foo();
Simply you can return the value in the function foo(). Or just use print_r to print the foo() value.
<?php
function foo()
{
echo 'Hello';
}
print_r (foo());
?>
The output will be Hello.
var_dump always shows the variable type like int or string or etc
When you call the function foo() and has no return type then print Hello and var_dump declares foo() is NULL since it has no return type.
<?php
function foo(){
echo 'Hello';
//return 'StackOverFlow';
}
var_dump(foo());
?>
Look this second one
<?php
function foo2(){
}
var_dump(foo2());
?>
output=>NULL
That means var_dump can't declare what type of variable function foo2()

Global scope not printing data

Why is $a not printing?
And what is the alternate of this, and I dont want to use return.
function abc () {
$a = 'abc';
global $a;
}
abc();
echo $a;
The reason why it's not echoing is because of two things:
1) You need to declare global "before" the variable you wish to define as being global.
and
2) You also need to call the function.
Rewrite:
<?php
function abc()
{
global $a;
$a = 'abc';
}
abc();
echo $a;
For more information on variable scopes, visit the PHP.net website:
http://www.php.net/manual/en/language.variables.scope.php
You can get your variable as:
echo $GLOBALS['a'];
see http://php.net/manual/en/language.variables.scope.php
You can use define():
function abc() {
define("A", "abc");
}
abc();
echo A;
Make sure you call the function. I added that just above echo.
First you must create and assign a variable. And then in you function describe that is a global var you want to use.
$a = 'zxc';
function abc() {
global $a;
$a = 'abc';
}
abc();
echo $a;
This is not really good idea to use golbal such way. I don't really understand why I so much want to use a global var...
But my opinion is better for you to use a pointer to variable.
function abc(&$var){
$var = 'abc';
}
$a = 'zxc';
abc(&$a);
echo $a;
Or even would be better to create an object and then access variable with-in this object

Is it possible to call a function when a variable changes in PHP?

function foo()
{ echo 'function called'; }
Is it possible to do something like this:
onchange($a, foo);
$a = "foo"; // echoes 'function called'
$a = "bar"; // echoes 'function called'
Instead of:
$a = "foo";
foo(); // echoes 'function called'
$a = "bar";
foo(); // echoes 'function called'
Sort of. You can use what's called a setter, a function designed to set a variable.
function setFoo ($value)
{
echo 'in setFoo';
return $value;
}
$a = setFoo('foo'); // echoes 'in setFoo'
echo $a; // echoes 'foo'
$a = setFoo('bar'); // echoes 'in setFoo'
echo $a; // echoes 'bar'
In short: no. You shouldn't use global variables anyway, what means, that foo() should not know anything about $a, except you give it as a parameter

PHP functions 101 question, really simple

I'm kind of slow in the head so can someone tell me why this isn't working:
function foo() {
$bar = 'hello world';
return $bar;
}
foo();
echo $bar;
I just want to return a value from a function and do something with it.
Because $bar does not exist outside of that function. Its scope is gone (function returned), so it is deallocated from memory.
You want echo foo();. This is because $bar is returned.
In your example, the $bar at the bottom lives in the same scope as foo(). $bar's value will be NULL (unless you have defined it above somewhere).
Your foo() function is returning, but you're not doing anything with it. Try this:
function foo() {
$bar = 'hello world';
return $bar;
}
echo foo();
// OR....
$bar = foo();
echo $bar;
You aren't storing the value returned by the foo function
Store the return value of the function in a variable
So
foo() should be replaced by
var $t = foo();
echo $t;
As the others have said, you must set a variable equal to foo() to do stuff with what foo() has returned.
i.e. $bar = foo();
You can do it the way you have it up there by having the variable passed by reference, like so:
function squareFoo(&$num) //The & before the variable name means it will be passed by reference, and is only done in the function declaration, rather than in the call.
{
$num *= $num;
}
$bar = 2;
echo $bar; //2
squareFoo($bar);
echo $bar; //4
squareFoo($bar);
echo $bar; //16
Passing by reference causes the function to use the original variable rather than creating a copy of it, and anything you do to the variable in the function will be done to the original variable.
Or, with your original example:
function foo(&$bar)
{
$bar = 'hello world';
}
$bar = 2;
echo $bar; //2
foo($bar);
echo $bar; //hello world

Lambda Functions in PHP aren't Logical

Note: I have condensed this article into my person wiki: http://wiki.chacha102.com/Lambda - Enjoy
I am having some troubles with Lambda style functions in PHP.
First, This Works:
$foo = function(){ echo "bar"; };
$foo();
Second, This Works:
class Bar{
public function foo(){
echo "Bar";
}
Third, This works:
$foo = new stdClass;
$foo->bar = function(){ echo "bar"; };
$test = $foo->bar;
$test();
But, this does not work:
$foo = new stdClass;
$foo->bar = function(){ echo "bar"; };
$foo->bar();
And, this does not work
class Bar{
public function foo(){
echo "Bar";
}
$foo = new Bar;
$foo->foo = function(){ echo "foo"; };
$foo->foo(); // echo's bar instead of Foo.
My Question is Why?, and how can I assure that both this:
$foo->bar = function(){ echo "test"; };
$foo->bar();
and this
$foo = new Bar;
$foo->bar();
are called properly? Extra Points if you can point to documentation stating why this problem occurs.
This is an interesting question. This works:
$a = new stdClass;
$a->foo = function() { echo "bar"; };
$b = $a->foo;
$b(); // echos bars
but as you say this doesn't:
$a = new stdClass;
$a->foo = function() { echo "bar"; };
$a->foo();
If you want an object to which you can dynamically call members, try:
class A {
public function __call($func, $args) {
$f = $this->$func;
if (is_callable($f)) {
return call_user_func_array($f, $args);
}
}
}
$a = new A;
$a->foo = function() { echo "bar\n"; };
$a->foo2 = function($args) { print_r($args); };
$a->foo();
$a->foo2(array(1 => 2, 3 => 4));
But you can't replace callable methods this way because __call() is only called for methods that either don't exist or aren't accessible (eg they're private).
Functions and methods are treated differently in PHP. You can use runkit_method_add() to add a method to a class, but I know of no way to add a method to an instance.
Interesting question although I see no reason why this should work:
class Bar{
public function foo(){
echo "Bar";
}
$foo = new Bar;
$foo->foo = function(){ echo "foo"; };
$foo->foo(); // echo's bar instead of Foo.
I had a similar problem with __invoke(), and I've also not been able to solve it:
class base {
function __construct() {
$this->sub = new sub();
}
function __call($m, $a) {
}
}
class sub {
function __invoke($a) {
}
}
$b = new base();
$b->sub('test'); // should trigger base::__call('sub', 'test') or sub::__invoke('test')?
Solution? Never use __invoke()! :P
The closest you could get to make this happen would be by using the __call overload to check if a property contains a closure:
class what {
function __call($name, $args) {
$f= $this->$name;
if ($f instanceof Closure) {
$f();
}
}
}
$foo = new what();
$foo->bar = function(){ echo "bar"; };
$foo->bar();
Though bear in mind the following note from the docs:
Anonymous functions are currently
implemented using the Closure class.
This is an implementation detail and
should not be relied upon.
Reference: Anonymous functions
The OP has already presented the solution:
$foo = new stdClass;
$foo->bar = function(){ echo "bar"; };
$test = $foo->bar;
$test();
I.e., any property that contains an anon function has an inherent ambiguity because adding parenthesis after the property name tells PHP that you are calling a method, and not invoking an anon function in a property. To resolve this ambiguity, you must add a degree of separation by storing the property into a local variable first, and then invoking the anon function.
You just have to look at the class property as a property instead of as "a property callable as a method" no matter what it's contents are and assume that php is going to look for a real class method if you put parenthesis after the property.
To me it seems like a bug rather than a "quirk":
<?php
$t = new stdClass;
$t->a = function() { echo "123"; };
var_dump($t);
echo "<br><br>";
$x = (array)$t;
var_dump($x);
echo "<br><br>";
$x["a"]();
echo "<br><br>";
?>
object(stdClass)#1 (1) { ["a"]=> object(Closure)#2 (0) { } }
array(1) { ["a"]=> object(Closure)#2 (0) { } }
123
It is there, I just don't think that PHP knows how to run it.
Consider this:
<?php
class A {
public $foo
public function foo() {
return 'The method foo';
}
}
$obj = new A;
$obj->foo = function() { return 'The closure foo'; };
var_dump($obj->foo());
Do you mean $obj->foo() the closure or $obj->foo() the method? It is ambiguous and PHP makes the decision that you mean the method. To use the closure, you have to disambiguate what you mean. One way you can do this is by using a temporary variable as you have done. Another way is to use call_user_func($obj->foo).
I do not know of any other easy way.

Categories