PHP ve MySQL en son sürümünü kullanıyorum - nesne bağlamında değil, $ zaman bu kullanma

3 Cevap

This is user.php:

    include("databse.php");//retrieving successfully first name and lastname from databse file into user.php
    class user
    {
      public $first_name;
      public $last_name;
      public static function full_name()
      {
          if(isset($this->first_name) && isset($this->last_name))
          {
            return $this->first_name . " " . $this->last_name;

          }
          else
           {
                return "";
           }
       }
    }

Diğer php dosyası, index.php:

   include(databse.php);
   include(user.php);
    $record = user::find_by_id(1);
    $object = new user();
    $object->id = $record['id'];
    $object->username = $record['username'];
    $object->password = $record['password'];
    $object->first_name = $record['first_name'];
    $object->last_name = $record['last_name'];
    // echo   $object->full_name();
    echo $object->id;// successfully print the id
    echo $object->username;//success fully print the username
    echo->$object->full_name();//**ERROR:Using $this when not in object context**

?>

3 Cevap

Eğer statik bir işlevi $this cant kullanmak. Kullan self:: yerine

Yap full_name non-static,

public function full_name() {}

Eğer statik bir yöntem örnek değişkenleri erişemiyor ancak yapmak çalıştığınız tam olarak ne olduğunu.

Eğer self yerine kullanırsanız $this, sen $first_name ve $last_name statik hem de beyan etmek zorunda.

Ben bile why Eğer ilk etapta static olarak bu yöntem bildirmek anlamıyorum. Bu elbette bir örnek yöntemidir.

Lütfen index.php son hattını kontrol edin. echo->$object->full_name() geçerli değil. echo $object->full_name() yerine kullanın.

Ayrıca, full_name() non-static olarak ilan.