SORU
18 Aralık 2010, CUMARTESİ


Alıcı ve Ayarlayıcı?

Ben bir PHP geliştirici, çok merak ediyorum eğer PHP daha popüler kullanımı açık bir alıcı/ayarlayıcı, saf bir OOP tarzı ile özel alanlar (ben gibi):

class MyClass {
    private $firstField;
    private $secondField;

    public function getFirstField() {
        return $this->firstField;
    }
    public function setFirstField($x) {
        $this->firstField = $x;
    }
    public function getSecondField() {
        return $this->secondField;
    }
    public function setSecondField($x) {
        $this->secondField = $x;
    }
}

ya da sadece kamu alanları

class MyClass {
    public $firstField;
    public $secondField;
}

Teşekkürler

CEVAP
18 Aralık 2010, CUMARTESİ


* __get *8 ve __set kullanabilirsiniz.

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Chriselle Lim

    Chriselle Li

    26 Ocak 2008
  • hydejiaqi

    hydejiaqi

    12 Mart 2008
  • John Lynn

    John Lynn

    8 Ocak 2010