PHP: başka bir işlev içinde önceden tanımlanmış bir fonksiyonun içinde bir değişken $ çağırmak nasıl?

2 Cevap php

Ben sadece Object Oriented PHP ile başladım ve şu sorunu var:

Belirli bir komut dosyası içeren bir işlev içeren bir sınıf var. Ben daha aynı sınıftan aşağı başka bir işlev içinde bu komut bulunan bir değişkeni çağırmak gerekir.

Örneğin:

class helloWorld {

function sayHello() {
     echo "Hello";
     $var = "World";
}

function sayWorld() {
     echo $var;
}


}

Yukarıdaki örnekte ben bir önceki işlev içinde tanımlanmış bir değişken $ var seslenmek istiyorum. Bu olsa çalışmıyor, bu yüzden bu nasıl yapabilirim?

2 Cevap

fonksiyon sona zaman değişken (nedeniyle fonksiyon sona ermesi) unset olacak çünkü, değil fonksiyonu, sınıfında VAR oluşturmanız gerekir ...

class helloWorld {

private $var;

function sayHello() {
     echo "Hello";
     $this->var = "World";
}

function sayWorld() {
     echo $this->var;
}


}
?>

Eğer public olarak değişkeni bildirirseniz size private olarak değişken bildirirseniz, sadece aynı sınıfta erişilebilir ise, bu, tüm diğer sınıflar tarafından doğrudan erişilebilir ..

<?php
 Class First {
  private $a;
  public $b;

  public function create(){
    $this->a=1; //no problem
    $thia->b=2; //no problem
  }

  public function geta(){
    return $this->a;
  }
  private function getb(){
    return $this->b;
  }
 }

 Class Second{

  function test(){
    $a=new First; //create object $a that is a First Class.
    $a->create(); // call the public function create..
    echo $a->b; //ok in the class the var is public and it's accessible by everywhere
    echo $a->a; //problem in hte class the var is private
    echo $a->geta(); //ok the A value from class is get through the public function, the value $a in the class is not dicrectly accessible
    echo $a->getb(); //error the getb function is private and it's accessible only from inside the class
  }
}
?>

Yapmak $var Bir sınıf değişkeni:

class HelloWorld {

    var $var;

    function sayHello() {
        echo "Hello";
        $this->var = "World";
    }

    function sayWorld() {
        echo $this->var;
    }

}

, Ben küresel bir, diğer bir sürü kod erişmek için gereken sürece önleyeceğini aynı sınıf içinde kullanılacak Sadece bir şey varsa, o zaman bir sınıf üyesi için mükemmel bir aday.

Lütfen sayHello() yöntemi sonradan çağırarak ise sayWorld(), daha sonra bir alternatif olduğunu yönteme argüman olacaktır.