PHP 等同于 Ruby 的 @instance_variable?

标签 php ruby this instance-variables

我想知道是否有更短、更好或更清晰的方法来分配和使用 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/

相关文章:

JavaScript 停止 "this"关键字在函数调用时发生变化?

c++ - 通过 lambda 调用成员函数时意外未初始化的数据

javascript - 在此上下文中,关键字 this 指的是什么?

php - magento 2.x 中 magento 1.x 模型的等效项是什么

php - 计算左尝试行

ruby - 在 ruby​​ 中将 JSON 转换为字符串或哈希

ruby - 无法通过gem “ssh-net”运行Ruby脚本

ruby - ruby代码是如何执行的

php - "Submitted form is invalid"将产品添加到购物车时 : Sylius Cart Bundle

php - 如何将变量作为 cURL 数组中的 url 参数传递给 CURLOPT_URL