简体   繁体   English

我可以更改 PHP 中 function 内的局部变量的值吗?

[英]Can i change the value of local variable sitting inside the function in PHP?

I was reading an article about Data Encapsulation in PHP, and the author explained in such a way that it made me to wonder if this is really possible?我正在阅读PHP中关于数据封装的文章,作者的解释让我怀疑这是否真的可能? here is what he said.这就是他所说的。

The primary purpose of encapsulation (scope) is to ensure that you write code that can't be broken.封装(范围)的主要目的是确保您编写的代码不会被破坏。 This applies to scope in general, so let me use a simpler example of a local variable inside a function:这通常适用于 scope,所以让我使用 function 中的局部变量的更简单示例:

function xyz ($x) {
  $y = 1;
  while ($y <= 10) {
    $array[] = $y * $x;
    $y++;
  }
  return $array;
}

The purpose of this function is to pass a number and return an array.这个 function 的目的是传递一个数字并返回一个数组。 The example code is pretty basic.示例代码非常基本。 In order for function xyz() to be dependable, you need to be guaranteed that it does the exact same thing every time.为了使 function xyz() 可靠,您需要保证它每次都执行完全相同的操作。 So what if someone had the ability to from the outside change that initial value of $y or $array?那么,如果有人能够从外部更改 $y 或 $array 的初始值呢? Or even $x?甚至$x? If you were able to do that from outside of the function, you could no longer guarantee what that function is returning.如果您能够从 function 外部执行此操作,则您无法再保证 function 将返回什么。

Now this made me wonder can i really change the value of local variable sitting inside the function without using any argument as demonstrated above??现在这让我想知道我真的可以在不使用上面演示的任何参数的情况下更改 function 内的局部变量的值吗? if it is possible how do i do it?如果可能的话,我该怎么做?

thank you..谢谢你..

For this example you wouldn't be able to change any of the variables, because they're all declared inside of the function.对于此示例,您将无法更改任何变量,因为它们都在 function 内部声明。

But if you had a class with a public class variable, you could change that outside of the class if you wanted to.但是,如果您有一个带有公共 class 变量的 class,如果您愿意,可以在 class 之外更改它。 (That's bad form and might screw a lot of things up, though.) (不过,这种形式很糟糕,可能会搞砸很多事情。)

Unless you add a magic setter method ( __set($key,$value) ), and configure it in such a way that you can access that internal member, then no.除非您添加一个神奇的 setter 方法( __set($key,$value) ),并以您可以访问该内部成员的方式对其进行配置,否则不会。 You can change the key when you make the function if you're using some form of factory, but if you haven't made it public, there's no other way.如果您使用某种形式的工厂,您可以在制作 function 时更改密钥,但如果您尚未公开,则没有其他方法。

The only visible exception would be with a singleton factory: you could make a new instance of your singleton method with different parameters (changing it everywhere else), but I doubt you'd be likely to do that with a method.唯一可见的例外是 singleton 工厂:您可以使用不同的参数(在其他任何地方更改它)创建 singleton 方法的新实例,但我怀疑您可能会使用方法来做到这一点。

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

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