簡體   English   中英

如何在課外使用 $this ?

[英]How to use $this in outside of class?

我們可以在課外使用$this嗎? 請看下面的例子,

<?php 

class Animal {

    public function whichClass() {
        echo "I am an Animal!";
    }

    public function sayClassName() {
        $this->whichClass();
    }
}

class Tiger extends Animal {

    public function whichClass() {
        echo "I am a Tiger!";
    }

    public function anotherClass() {
        echo "I am a another Tiger!";
    }

}

$tigerObj = new Tiger();

//Tiger::whichClass();

$this->anotherClass();

在這里我創建了新對象$tigerObj = new Tiger(); 之后我嘗試使用$this但它拋出錯誤。 那么可以在課堂外使用$this嗎? 如果不是, $this指的是當前對象。 那么我們為什么不使用它呢?

$ this不可能在外部類中使用,因此您可以創建靜態方法,並像Tiger :: anotherClass這樣使用。 鏈接到文檔

class Animal {

    public function whichClass() {
        echo "I am an Animal!";
    }

    public function sayClassName() {
        $this->whichClass();
    }
}

class Tiger extends Animal {

    public function whichClass() {
        echo "I am a Tiger!";
    }

    public static function anotherClass() {
        echo "I am a another Tiger!";
    }

}

$tigerObj = new Tiger();

//Tiger::whichClass();

Tiger::anotherClass();

不可能以這種方式使用$ this,可以創建該類的對象,然后擴展要調用的方法。 見下文 ...

class Animal {

    public function whichClass() {
        echo "I am an Animal!";
    }

    public function sayClassName() {
        $this->whichClass();
    }
}

class Tiger extends Animal {

    public function whichClass() {
        echo "I am a Tiger!";
    }

    public function anotherClass() {
        echo "I am a another Tiger!";
    }

}

$tigerObj = new Tiger();

echo $tigerObj->anotherClass();

您將得到結果“我是另一只老虎!”

不,您不能在類范圍之外使用$ this

例如:

1    $this=new \DateTime();
2    echo $this->format('r');

產生以下錯誤:

Fatal error: Cannot re-assign $this on line 2

是的,可以在 php 8 中使用$this外部類。

示例: class.php

<?php
class MyClass {
  private $say = '';
  public function say(string $text) {
    $this->say = $text;
  }

  public function hear() {
    require __DIR__ . '/test.php';
    echo $this->say;
  }
}
$MyClass = new MyClass();
$MyClass->hear();
?>

test.php

<?php
$this->set('Using this Outside Class Is Possible');
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM