SORU
9 Kasım 2009, PAZARTESİ


En iyi yolu PHP çoklu kurucular yapmak

PHP bir sınıf benzersiz değişken imzalı __iki yapı fonksiyonları koyamazsınız. Bunu yapmak istiyorum:

class Student 
{
   protected $id;
   protected $name;
   // etc.

   public function __construct($id){
       $this->id = $id;
      // other members are still uninitialized
   }

   public function __construct($row_from_database){
       $this->id = $row_from_database->id;
       $this->name = $row_from_database->name;
       // etc.
   }
}

PHP bunu yapmak için en iyi yolu nedir?

CEVAP
9 Kasım 2009, PAZARTESİ


Muhtemelen böyle bir şey yapardım:

<?php

class Student
{
    public function __construct() {
    	// allocate your stuff
    }

    public static function withID( $id ) {
    	$instance = new self();
    	$instance->loadByID( $id );
    	return $instance;
    }

    public static function withRow( array $row ) {
    	$instance = new self();
    	$instance->fill( $row );
    	return $instance;
    }

    protected function loadByID( $id ) {
    	// do query
    	$row = my_awesome_db_access_stuff( $id );
    	$this->fill( $row );
    }

    protected function fill( array $row ) {
    	// fill all properties from array
    }
}

?>

Eğer KİMLİĞİNİ biliyorum bir Öğrenci istersem o zaman:

$student = Student::withID( $id );

Ya eğer db satır bir dizi var:

$student = Student::withRow( $row );

Teknik olarak birden fazla kurucular, statik yardımcı yöntemler sadece bina değilsin, ama makarna yapıcısı bu şekilde kod bir sürü önlemek için.

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

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • eisleyhead

    eisleyhead

    11 Ocak 2006
  • Jucyber Tutoriais

    Jucyber Tuto

    8 EYLÜL 2009
  • MaximumPCMag

    MaximumPCMag

    23 Temmuz 2010