您从 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 的基本部分。