【问题标题】:php: when need to use self::method()? [duplicate]php:什么时候需要使用self::method()? [复制]
【发布时间】:2013-08-23 06:36:34
【问题描述】:
<?php

class MyClass
{
    public $prop1 = "I'm a class property!";

    public function __construct()
    {
        echo 'The class "', __CLASS__, '" was initiated!<br />';
    }

    public function __destruct()
    {
        echo 'The class "', __CLASS__, '" was destroyed.<br />';
    }

    public function __toString()
    {
        echo "Using the toString method: ";
        return $this->getProperty();
    }

    public function setProperty($newval)
    {
        $this->prop1 = $newval;
    }

    public function getProperty()
    {
        return $this->prop1 . "<br />";
    }
}

class MyOtherClass extends MyClass
{
    public function __construct()
    {
        parent::__construct(); // Call the parent class's constructor
        $this->newSubClass();
    }

    public function newSubClass()
    {
        echo "From a new subClass " . __CLASS__ . ".<br />";
    }
}

// Create a new object
$newobj = new MyOtherClass;


?>

问题:

如果把$this-&gt;newSubClass();改成self::newSubClass();也可以,那么什么时候用$this-&gt;newSubClass();,什么时候用self::newSubClass();

【问题讨论】:

  • self:: 用于静态方法 / $this 用于 obj 本身。
  • self 几乎从来不是你的意思,通常你想使用static。查看late static binding的信息

标签: php


【解决方案1】:

使用self::methodName 对该方法进行静态调用。你不能使用$this,因为你不在一个对象的上下文中。

Try this:

class Test
{
    public static function dontCallMeStatic ()
    {
         $this->willGiveYouAnError = true;
    }
}

Test::dontCallMeStatic();

你应该得到以下错误:

致命错误:当不在对象上下文中时使用 $this...

【讨论】:

    【解决方案2】:

    据我所知,如果您在 $this-&gt;newSubClass(); 中使用 -&gt;,它用于访问对象的实例成员,尽管它也可以访问静态成员,但不鼓励这种用法。

    那么对于这个self::newSubClass();中的::,通常用于访问静态成员,但一般来说,这个符号::可用于scope resolution,它可能有一个类名、父级、自身或(在 PHP 5.3 中)左侧是静态的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-22
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 2012-09-16
      相关资源
      最近更新 更多