1

In ruby a lot of methods have the ! marker which usually means a variable will be modified in place. So you could do

p "HELLO".downcase!

which is the same as

s = "HELLO".downcase
p s

In php you can use a pointer with the ampersand & symbol before a variable to modify it in place, or handle the var as a pointer. But does a function modifier exist or variable modifier that would allow for in place modification of varibales like

$str = "hi world";
str_replace("hi", "world", &$str)

3 Answers 3

2

Even in Ruby, the ! versions of functions are alternative versions specifically created to modify the variable in place. I.e. downcase and downcase! are two completely different functions, the ! is just a naming convention.

In PHP, you can pass variables by reference into any function, as you have shown yourself, but this may not necessarily give you the expected result, entirely depending on what the function does internally with the variable. To get a result similar to Ruby, you'd have to define an alternative version of each function that modifies in place:

// PHP doesn't allow ! in function names, using _ instead
function str_replace_($needle, $replacement, &$haystack) {
    $haystack = str_replace($needle, $replacement, $haystack);
}
Sign up to request clarification or add additional context in comments.

2 Comments

If you want to return reference from function, its declaration must also contain ampersand before name - as in my answer.
@Tomasz Indeed, but that's unrelated to the question. :)
1

There are no pointers in PHP - only references. If you want to learn what is possible to do with them, here is a link for you:

http://php.net/manual/en/language.references.php

You want to return reference, so please read this example:

<?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.
?>

Comments

0

You can not modify the behavior of a function, although some functions to take a pointer an argument for modification. These functions generally return a boolean value to indicate if the function was successful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.