JavaScript Pass Variables Through Reference - php

Is there an equivalent in JavaScript for PHP's reference passing of variables?
[PHP]:
function addToEnd(&$theRefVar,$str)
{
$theRefVar.=$str;
}
$myVar="Hello";
addToEnd($myVar," World!");
print $myVar;//Outputs: Hello World!
How would the same code look in JavaScript if possible?
Thank you!

Objects are passed as references.
function addToEnd(obj,$str)
{
obj.setting += $str;
}
var foo = {setting:"Hello"};
addToEnd(foo , " World!");
console.log(foo.setting); // Outputs: Hello World!
Edit:
As posted in comments below, CMS made mention of a great article.
It should be mentioned that there is no true way to pass anything by reference in JavaScript. The first line has been changed from "by reference" to "as reference". This workaround is merely as close as you're going to get (even globals act funny sometimes).
As CMS, HoLyVieR, and Matthew point out, the distinction should be made that foo is a reference to an object and that reference is passed by value to the function.
The following is included as another way to work on the object's property, to make your function definition more robust.
function addToEnd(obj,prop,$str)
{
obj[prop] += $str;
}
var foo = {setting:"Hello"};
addToEnd(foo , 'setting' , " World!");
console.log(foo.setting); // Outputs: Hello World!

In Javascript there is no passing variable by reference like in PHP. There is a possible workaround to do something similar.
function addToEnd(obj, str)
{
obj.value += str;
}
myVar={value:"Hello"};
addToEnd(myVar, " World");
alert(myVar.value); //Outputs: Hello World!
In this example, what happens is that you pass an object to the function and inside of it, you are modifying the object (not the variable, the variable is still pointing to the same object). This is why this is not passing variable by reference has vol7ron incorrectly stated.

The other answers/comments describe the situation well enough, but I thought I'd offer and alternative if you need that style of functionality, by using a callback.
var someText = "asd";
addToEnd(someText, "fgh", function(val) { someText = val; });
and
function addToEnd(original, str, setValue)
{
setValue(original += str);
}
but a better solution would be
var someText = "asd";
someText = addToEnd(someText, "fgh");
and
function addToEnd(original, str)
{
return original += str;
}

try this:
// function
function func(param,callback){
if(param){
if(typeof callback=='function') {
callback.call(this,param);
}
return true;
}
return false;
}
// calling function
var variable=0;
returnValue=func(10,function(reference){variable=reference});
alert(returnValue+'/'+variable);

Related

How to define function name using variable?

how to define function name (in PHP) using variable, like this?
$a='myFuncion';
function $a() {.......}
or like that?
The only way I know to give a fixed name to a function is to use eval, which I would not suggest.
More likely, what you want is to stuff a function IN a variable, and then just call that.
Try this:
$a = function() {
echo 'This is called an anonymous function.';
}
$a();
EDIT:
If you want to be accessible from other files, then use GLOBAL variable:
$GLOBALS['variable_name'] = 'my_func_123';
${$GLOBALS['variable_name']} = function() {
echo 'This is called an anonymous function.';
};
// Executing my_func_123()
${$GLOBALS['variable_name']}();
See also: http://php.net/manual/en/functions.anonymous.php

PHP: newbie question - something like with/end with in php?

is there something like with/end with (like in asp) for php?
especially for class objects it would be nice - asp syntax is like:
with myWeb
.init "myweb"
response.write .html
end with
thanks
No, there is no such thing in PHP : you have to write the full name of classes / objects / variables / whatever when you want to use them.
No, AFAIK.
Do you really find this syntax useful ?
No, but there is an alternative syntax for control structures that may interest you.
not sure im right but tryed my best to translate your example :/
<?php function write_block(){
echo '.html';
}
die(write_block());
?>
It's not exactly what you wanted, but you can do something similar with PHP references:
<?php
class A {
public $bar1 = 1;
public $bar2 = 2;
public $bar3 = 3;
}
class B {
public $foo;
}
class C {
public $foobar;
}
$myC = new C;
$myC->foobar = new B;
$myC->foobar->foo = new A;
print $myC->foobar->foo->bar1;
print $myC->foobar->foo->bar2;
print $myC->foobar->foo->bar3;
//Simpler with 'With...End With syntax:
//which might look something like:
//
// with ($myC->foobar->foo) //Note this is not valid PHP
// {
// print ->bar1; //Note this is not valid PHP
// print ->bar2; //Note this is not valid PHP
// print ->bar3; //Note this is not valid PHP
// }
//
//Fortunately, you can sort of do this using an object reference:
//
$obj =& $myC->foobar->foo;
print $obj->bar1;
print $obj->bar2;
print $obj->bar3;
unset ($obj);
?>

Is it possible to obtain the code from an anonymous function in PHP?

Suppose I have an anonymous function:
$func = function() { return true; }
I want to (dynamically) obtain the string "return true;" from the variable $func.
You can reflect such function:
$test = function() { return true; };
$r = new ReflectionFunction($test);
var_dump($r->getName());
However from what I can see in manual, PHP's reflection API doesn't provide any method that would return function's source. You can obtain start and end line of function declaration, what combined with such code-style:
$test = function() {
return false;
}
Will let you quite easily obtain function's source. But remember that this is very tricky and as #Col. Shrapnel and #DampeS8N mentioned: you really don't want to do that.
No you can't. The code is parsed and no string representation exists.

How do I immediately execute an anonymous function in PHP?

In JavaScript, you can define anonymous functions that are executed immediately:
(function () { /* do something */ })()
Can you do something like that in PHP?
For versions prior to PHP 7, the only way to execute them immediately I can think of is
call_user_func(function() { echo 'executed'; });
With current versions of PHP, you can just do
(function() { echo 'executed'; })();
In PHP 7 is to do the same in javascript
$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;
The output is:
1
2
3
This is the simplest for PHP 7.0 or later.
(function() {echo 'Hi';})();
It means create closure, then call it as function by following "()". Works just like JS thanks to uniform variable evaluation order.
https://3v4l.org/06EL3
Well of course you can use call_user_func, but there's still another pretty simple alternative:
<?php
// we simply need to write a simple function called run:
function run($f){
$f();
}
// and then we can use it like this:
run(function(){
echo "do something";
});
?>
(new ReflectionFunction(function() {
// body function
}))->invoke();
Note, accepted answer is fine but it takes 1.41x as long (41% slower) than declaring a function and calling it in two lines.
[I know it's not really a new answer but I felt it was valuable to add this somewhere for visitors.]
Details:
<?php
# Tags: benchmark, call_user_func, anonymous function
require_once("Benchmark.php");
bench(array(
'test1_anonfunc_call' => function(){
$f = function(){
$x = 123;
};
$f();
},
'test2_anonfunc_call_user_func' => function(){
call_user_func(
function(){
$x = 123;
}
);
}
), 10000);
?>
Results:
$ php test8.php
test1_anonfunc_call took 0.0081379413604736s (1228812.0001172/s)
test2_anonfunc_call_user_func took 0.011472940444946s (871616.13432805/s)
This isn't a direct answer, but a workaround. Using PHP >= 7. Defining an anonymous class with a named method and constructing the class and calling the method right away.
$var = (new class() { // Anonymous class
function cool() { // Named method
return 'neato';
}
})->cool(); // Instantiate the anonymous class and call the named method
echo $var; // Echos neato to console.
I tried it out this way, but it's more verbose than the top answer by using any operator (or function) that allows you to define the function first:
$value = $hack == ($hack = function(){
// just a hack way of executing an anonymous function
return array(0, 1, 2, 3);
}) ? $hack() : $hack();
Not executed inmediately, but close to ;)
<?php
$var = (function(){ echo 'do something'; });
$var();
?>

How to properly work _around_ Javascript persistence?

There is basic persistence of Javascript vars/etc. You call a function/method, and the next time you call that same function/method, it is holding the data from the last time.
You can delete the vars when you are done with them, but that removes the advantage of using the code again for that instance.
So what is the proper way to write code which can be reused, on different elements, inside the same page.
Therefore, I need the ability to write code so that I can point it at several different elements, and then interact with that code segregated for each element.
So in PHP (as an example) I would do:
$element1 = new MyClass();
$element2 = new MyClass();
$element3 = new MyClass();
in that case it's the same code running in three segregated scopes. How can I do this properly with JS. Even using jQuery's extend() gives me problems.
Thanks.
Use the var keyword when defining local variables (otherwise they'll default to globals).
function foo() {
var i;
// code code code code
}
To create an instance in JavaScript you need to write a constructor function, and call that using new. For instance:
function MyClass( somevalue ) {
this.somevalue = somevalue;
this.somefunction = function() {
alert(somevalue);
}
}
var instance1 = new MyClass(1);
var instance2 = new MyClass(2);
var instance3 = new MyClass(3);
You can namespace your JavaScript to make it a lot like what you're after. See below for an example. It does sound like your problem is related to using global variables where you want to use local variables though - i.e. you declare var myvariable; outside of your function, but only want to use it and forget it within your function. In that case, declare the variable inside your function to make it local.
var MyNameSpace = function() {
return {
sayhello : function() {
alert("hello");
},
saygoodbye : function() {
alert("see ya");
}
};
}();
It sounds like what you're looking for is the ability to have instances of a class and have private data that's associated with each instance.
You can do this using the following technique:
function Foo()
{
// Member variable only visible inside Foo()
var myPrivateVar;
// Function only visible inside Foo()
var myPrivateFunction = function()
{
alert("I'm private!");
}
// Member variable visible to all
this.myPublicVar = "Hi, I'm public!";
// Function visible to all
this.myPublicFunction = function()
{
myPrivateVar = "I can set this here!";
}
}
You can create and use one of these using the following syntax:
var myFoo = new Foo();
myFoo.myPublicVar = "I can set this!";
myFoo.myPublicFunction();

Categories