我想知道是否有更短、更好或更清晰的方法来分配和使用 PHP 中的类变量,然后通过 $this->instance_variable
?
class Bar {
# internal variables
var $foo = "Hello World";
public function foo() {
return $this->foo;
}
}
我不是很熟悉 PHP 的所有变量作用域,但根据我在官方文档中的理解,您可以将它们定义为全局,或者通过 $this->
访问它们?
是否有关键字将它们定义为实例变量,因此可以像 Rubys @variable 一样访问它们?
最佳答案
您从 ruby 中得出的一些关键假设不能很好地转换为 PHP。
在PHP中声明和使用对象属性(相当于Ruby的实例变量)的正确方法是
class Foo
{
//accesible from inside this objects of this class,
//objects that have this class as an ancestor, and from
//outside the object
//var $bar; is equivalent. "var" is PHP 4 syntax,
//when everything was public
public $bar;
//accesible from inside this objects of this class,
//objects that have this class as an ancestor
protected $baz;
//accesible from inside this objects only
private $fiz;
protected function example()
{
echo $this->bar . "\n";
echo $this->baz . "\n";
echo $this->fiz . "\n";
}
}
PHP 的 OO 语法基于 Java/C# 世界观。但是,因为每个 PHP 页面/脚本/程序都从全局分数开始,所以需要对本地对象的 $this
伪引用。没有它,您会在这种情况下产生很大程度的歧义
//In main.php
$foo = "bar";
include('example.php');
//in example.php
class Example
{
public $foo="baz";
public function scopeIsHardLetsGoShopping()
{
global $foo;
echo $foo;
}
}
那么,方法中引用的$foo应该是对象变量,还是全局变量呢?如果你说它应该是对象变量,你如何从方法访问全局 foo ?如果你说它应该是全局变量,你如何在声明一个具有相同名称的全局变量后访问局部属性?
Ruby 和 Python 在语言诞生之初就对作用域进行了一些思考,因此这些问题是可以避免的。 PHP 最初是一种快速破解某些 C 代码以处理表单和输出 HTML 的方法。因为 PHP 做出了合理的努力来实现向后兼容,所以您最终会遇到像 $this 这样古怪的解决方法。
来自 Ruby,它看起来有点冗长,但它是 PHP 的基础部分。
关于PHP 等同于 Ruby 的 @instance_variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3907958/