genişletilmiş sınıflar için bir __ construct () eşdeğer olduğu

3 Cevap php

Ben bir üst sınıf var:

Abstract Class Base {
    function __construct($registry) {
        // stuff
    }
}

Ben o sınıfını genişletmek en az 2 sınıfları var

class Cms extends Base {
   // a few functions here
}

ve bu

class Index extends Base {
   // a few functions here
}

Oturum önceden başlatılmış olan ve kullanıcı bir oturum var kullanarak tarafından kaydedilir olmadığını kontrol etmek istiyorum in CMS sınıf için, kullanıcı oturum açmış olmanız gerekir. Peki ne yapmak istiyorum olduğunu:

class Cms extends Base {
   function __construct()
   {
        // check the user session is valid
   }
   // a few functions here
}

ama tabii üst yapı sınıfı ve set şeyi değiştireceği anlamına. Bir __ construct çocuk sınıfta tanımlanabilir () tipi yöntemi için bir yolu var mı?

3 Cevap

Çocuk yapıcısı itibaren, ebeveyn tek çağırabilirsiniz:

class Cms extends Base {
   function __construct()
   {
       parent::__construct();
        // check the user session is valid
   }
   // a few functions here
}

Kılavuzun Constructors and Destructors sayfası ve not örneklere bakın (quoting):

Note: Parent constructors are not called implicitly if the child class defines a constructor.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Bir sınıf 'kurucu çağırma php kadar automagically balonu yok. Elle ebeveynin kurucusuna bir çağrı eklemek zorunda. (Ve ben bir kusur olduğunu düşünün.)

class Cms extends Base {
   function __construct()
   {
       parent::__construct(); 
       // check the user session is valid
   }
   // a few functions here
}

PHP: Scope Resolution Operator (::) diyor ki:

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Eğer __ set () geçersiz kılmak, size de üst sınıfında belirtilen tüm davranış almak sağlamak için aynı kodu (parent :: __method) kullanabilirsiniz, yani sınıf uzantıları ile uğraşırken Bu çözüm aynı zamanda tüm php sihirli yöntemler için de geçerlidir.

VolkerK: Neden bu bir kusur olurdu? Varsayım size, bu davranışı değiştirmek istediğiniz bir yöntem için temel sınıflar davranışını geçersiz eğer aksi özellikle beyan olmadıkça gibi görünmektedir. Ben bir yöntem genişletmek olabilir eğer çok üzücü buluyorum, ama her zaman üst sınıf varsayılan davranış olarak adlandırılan, hem de ben yapıyordum ne olur. Diğer OO dilleri bu şekilde uygulamak mı?