class foo {
public function bar(){
$var = 10;
return $var
}
}
I have this class in one file, can i call this class and function in another file and somehow edit the variable $var, and then store it to the same variable so it can be used after in the class?
我在一个文件中有这个类,我可以在另一个文件中调用这个类和函数,并以某种方式编辑变量$ var,然后将它存储到同一个变量中,以便在类之后使用它吗?
1 个解决方案
#1
0
You cannot "reach into" functions and change variables used within them. From a sort of theoretical computer science standpoint, it doesn't even make sense. The variable $var
only exists while the function is executing. When you call $foo->bar()
, the code in it runs, creating the local variable $var
, assigning 10
to it, then returning it. Then the whole scope is destroyed and the variable $var
ceases to exist. It's not possible to alter it at all from code outside of Foo::bar
, because it doesn't exist while code outside of Foo::bar
is running. That's no to mention variable scope or encapsulation at all...
您无法“进入”功能并更改其中使用的变量。从某种理论计算机科学的角度来看,它甚至没有意义。变量$ var仅在函数执行时存在。当你调用$ foo-> bar()时,它中的代码会运行,创建局部变量$ var,为它分配10,然后返回它。然后整个范围被破坏,变量$ var不再存在。根本不可能从Foo :: bar之外的代码改变它,因为在Foo :: bar之外的代码运行时它不存在。这根本就没有提到变量范围或封装......
Most likely you'll want a property:
你最有可能想要一个房产:
class Foo {
public $var = 10;
public function bar(){
return $this->var;
}
}
Public properties are a bad idea in and of themselves in most OO contexts, but that's a different cattle of fish I won't go into here.
在大多数面向对象的环境中,公共财产本身并不是一个坏主意,但这是不同的鱼群,我不会在这里讨论。
#1
0
You cannot "reach into" functions and change variables used within them. From a sort of theoretical computer science standpoint, it doesn't even make sense. The variable $var
only exists while the function is executing. When you call $foo->bar()
, the code in it runs, creating the local variable $var
, assigning 10
to it, then returning it. Then the whole scope is destroyed and the variable $var
ceases to exist. It's not possible to alter it at all from code outside of Foo::bar
, because it doesn't exist while code outside of Foo::bar
is running. That's no to mention variable scope or encapsulation at all...
您无法“进入”功能并更改其中使用的变量。从某种理论计算机科学的角度来看,它甚至没有意义。变量$ var仅在函数执行时存在。当你调用$ foo-> bar()时,它中的代码会运行,创建局部变量$ var,为它分配10,然后返回它。然后整个范围被破坏,变量$ var不再存在。根本不可能从Foo :: bar之外的代码改变它,因为在Foo :: bar之外的代码运行时它不存在。这根本就没有提到变量范围或封装......
Most likely you'll want a property:
你最有可能想要一个房产:
class Foo {
public $var = 10;
public function bar(){
return $this->var;
}
}
Public properties are a bad idea in and of themselves in most OO contexts, but that's a different cattle of fish I won't go into here.
在大多数面向对象的环境中,公共财产本身并不是一个坏主意,但这是不同的鱼群,我不会在这里讨论。