0

Is there any way to get the current, after previous value of a variable while setting it? I mean:

$x = 10
$x = id() + 20; // 30

function id() {
   return THE_VARIABLE_VALUE; // 10
}

Or do I need be explicit and say (?):

$x = 10
$x = id($x) + 20; // 30

function id($x) {
   return $x; // 10
}

My question is:

In PHP, can I get implicitly the value of a variable?

id is trying to simulate the very known id function, that returns the own element:

id = (xs) -> xs
id 1 -- 1
id 'k' -- k
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Marcelo Camargo
  • 2,240
  • 2
  • 22
  • 51
  • 1
    Afaik this is not possible in PHP. I don't know for what this can be useful either. Is better and cleaner code if you give paramters into the function and get a return value. – TiMESPLiNTER Oct 01 '14 at 13:48
  • A variable contains one value. It doesn't store its own history. For such purposes, we have data structures such as arrays which you can use to implement such functionality. Also, I have never heard of the "very known id function". Are you referring to auto_increment of some sort? – N.B. Oct 01 '14 at 13:50
  • 1
    @N.B. I believe his is refering to this: http://stackoverflow.com/questions/3136338/uses-for-haskell-id-function i cant say i am any the wiser for reading it though! – Steve Oct 01 '14 at 13:52
  • @Steve - thanks for the link, I must admit that I'm in the same boat as you after reading it :) – N.B. Oct 01 '14 at 13:56
  • 1
    In Haskell, just like in PHP, `id` can't magically guess what variable you're talking about. It has to be passed a value, like `x`, and then it returns that same value. You can't just call `id` and get 10 because you were thinking of 10 a minute ago. – amalloy Oct 01 '14 at 23:49

2 Answers2

0

Well... for simple math, you could use the built in "modify this variable" operators:

$x += 20;
$x -= 10;
$x *= 5;
$x /= 3;

I'm not sure what you're trying to accomplish here, so other than that not much I can say. Maybe try explaining what your goal is here?

Erik
  • 1,057
  • 7
  • 11
0

As far as I know, you can use functions directly as the type of their return value, so you can do operations and function calls on them. On my localhost I have php 5.4 and I can do stuff like $myarray_element = get_my_array()[0]; or $mynumber = get_my_array_element()+10;. You can't do things likeget_my_array_element()++; or $var = get_my_array_element()++;.

Krisztián Dudás
  • 856
  • 10
  • 22