php kod yürütme değil mi?

6 Cevap php
<?php
class abhi
{
    var $contents="default_abhi";

    function abhi($contents)
    {
        $this->$contents = $contents;
    }

    function get_whats_there()
    {
        return $this->$contents;
    }

}

$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();

?>

Ben Değişken içeriği varsayılan ve aynı zamanda kurucu, neden değer baskı değil, ben burada düzeltmek gereken bir şey başlatıldı var?

hata görmek,

abhilash@abhilash:~$ php5 pgm2.php 

Fatal error: Cannot access empty property in /home/abhilash/pgm2.php on line 13
abhilash@abhilash:~$ 

6 Cevap

Sen işlev içinde yanlış değişken dönüyor. Bu olmalıdır:

return $this->contents

Soru olarak etiketlenmiş yana "php 5" Burada (php5 class notation (yani kamu / korumalı / var yerine, kamu / korumalı / özel fonksiyonu özel, __ yapısı ile kendi sınıfının bir örneği ) kullanılarak classname of (), ...)

class abhi {
  protected $contents="default_abhi";

  public function __construct($contents) {
    $this->contents = $contents;
  }

  public function get_whats_there() {
    return $this->contents;
  }
}

$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();

Doğru geri çağırmak durumunda olurdu

$this->contents = $contents;

değil

$this->$contents = $contents;

Erişme ve $ yazılı olmalı bu-> içerikleri bu-> $ içeriğini $ değil

Ayrıca, bir dolar işareti eksik değildir "echo abhilash-> get_whats_there ();"? ($ Abhilash-> ..)

You have a problem with $: 1. when using $this-> you do not put $ between "->" and the variable name the "$" sign, so your $this->$contents should be $this->contents. 2. in your echo youforgot the $ when calling that function from the instantiated class.

Yani doğru kod:

<?php
class abhi
{
    var $contents="default_abhi";

    function abhi($contents)
    {
        $this->contents = $contents;
    }

    function get_whats_there()
    {
        return $this->contents;
    }

}

$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();

?>