简体   繁体   English

在php函数中使用指针或修饰符

[英]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 pointer. 在php中,您可以在变量前使用带有&符号的指针来修改它,或将var作为指针处理。 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 ! 即使在Ruby中, ! versions of functions are alternative versions specifically created to modify the variable in place. 函数的版本是专门创建用来修改变量的备用版本。 Ie downcase and downcase! downcasedowncase! 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. 在PHP中,您可以通过引用将变量传递给任何函数,如您所展示的那样,但这不一定能给您预期的结果,这完全取决于函数在变量内部进行的操作。 To get a result similar to Ruby, you'd have to define an alternative version of each function that modifies in place: 为了获得与Ruby类似的结果,您必须为每个修改后的函数定义一个替代版本:

// 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. PHP中没有指针-仅引用。 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 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. 这些函数通常返回一个布尔值,以指示该函数是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM