开发者

Using pointers or modifiers in php functions

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 poin开发者_Python百科ter. 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)


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);
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜