Le domande dicono tutto davvero.
Ho delle costanti definite nella mia classe genitore. Ho provato $this->CONSTANT_1
ma non funziona
class MyParentClass{
const CONSTANT_1=1
}
class MyChildClass extends MyParentClass{
//want to access CONSTANT_1
}
Penso che avresti bisogno di accedervi in questo modo:
MyParentClass::CONSTANT_1
o "genitore", come è stato menzionato.
Interessante
Una cosa che è interessante notare è che puoi effettivamente sovrascrivere il valore const nella classe child.
class MyParentClass{
const CONSTANT_1=1
}
class MyChildClass extends MyParentClass{
const CONSTANT_1=2
}
echo MyParentClass::CONSTANT_1 // outputs 1
echo MyChildClass::CONSTANT_1 // outputs 2
Puoi anche accedere alla definizione costante nei bambini dal metodo genitore, con il statico chiave.
<?php
class Foo {
public function bar() {
var_dump(static::A);
}
}
class Baz extends Foo {
const A = 'FooBarBaz';
public function __construct() {
$this->bar();
}
}
new Baz;
<?php
class MyParentClass{
const CONSTANT_1=123;
}
class MyChildClass extends MyParentClass{
public static function x() {
echo parent::CONSTANT_1;
}
}
MyChildClass::x();
Esempio dal vivo: http://codepad.org/Yqgyc6MH
Non devi usare parent
. Puoi usare self
quale prima controllerebbe se c'è constant
con lo stesso nome nel class
stesso, quindi proverebbe ad accedere al parents
constant
.
Così self
è più versatile e offre la possibilità di "sovrascrivere" il parents
constant
, senza sovrascriverlo in quanto è ancora possibile accedervi esplicitamente tramite parent::
.
Seguente struttura:
<?php
class parentClass {
const MY_CONST = 12;
}
class childClass extends parentClass {
public function getConst() {
return self::MY_CONST;
}
public function getParentConst() {
return parent::MY_CONST;
}
}
class otherChild extends parentClass {
const MY_CONST = 200;
public function getConst() {
return self::MY_CONST;
}
public function getParentConst() {
return parent::MY_CONST;
}
}
Porta ai seguenti risultati:
$childClass = new childClass();
$otherChild = new otherChild();
echo childClass::MY_CONST; // 12
echo otherChild::MY_CONST; // 200
echo $childClass->getConst(); // 12
echo $otherChild->getConst(); // 200
echo $childClass->getParentConst(); // 12
echo $otherChild->getParentConst(); // 12
Uso genitore, per esempio:
class MyParentClass{
const CONSTANT_1=1;
}
class MyChildClass extends MyParentClass{
function __construct(){
echo parent::CONSTANT_1; //here you get access to CONSTANT_1
}
}
new MyChildClass();
O:
class MyParentClass{
const CONSTANT_1=1;
}
class MyChildClass extends MyParentClass{
MyParentClass::CONSTANT_1; // here you you get access to CONSTANT_1 too
}