php - Access parent class array in child class - php

class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database = [
'APP_DB_HOST' => $settings->constants['database']['APP_DB_HOST'], // not working
];
}
I need to access parent class array values in child class. but this $settings->constants['database']['APP_DB_HOST'] is not working for some reason.

Here is the working solution
<?php
class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database;
public function __construct(){
$database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
}
}
print_r(new Constants());
outputs:
Constants Object
(
[database] =>
[constants] => Array
(
[database] => Array
(
[APP_DB_HOST] => localhost
)
)
)
as per your comment,
if you want to do it in other class function, you can do that as well.
class Constants extends Settings {
public $database;
public function useParentHost(){
$this->database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
return $this->database;
}
}
and then
$test = new Constants();
print_r($test->useParentHost());
you have to declare some function to use $this, without/outside the function this will cause an error.

The variable $settings does not exist, perhaps you mean $this?
$this->constants['database']['APP_DB_HOST'];
Enjoy.

Related

Access a static variable in a class

The example below has a syntax error because of the following code:
"another_key" => [ 2 => self::$someStr ]
Using something such as:
"another_key" => [ 2 => "bar" ]
Is correct syntax. Is there any way to access $someStr instead of hard coding the string?
<?php
class Foo {
protected static $someStr = 'bar';
private static $arr = [
"some_key" => [ 1 ],
"another_key" => [ 2 => self::$someStr ]
];
}
You cannot access static variables inside of the declaration of other static variables. You can either declare a class constant or initialize it by accessing via a function. A class constant would look like this:
class Foo {
const someStr = 'bar';
private static $arr = [
"some_key" => [ 1 ],
"another_key" => [ 2 => self::someStr ]
];
}
Or using a function:
class Foo {
private static $someStr = 'bar';
private static $arr = [
"some_key" => [ 1 ],
"another_key" => [ 2 => null ]
];
private static function setKey(){
self::$arr['another_key'] = [2 => self::$somStr];
}
}
You'd then have to call Foo::setKey() at some point before accessing the variable.
If you want to access a property to set the value of another property you should be doing it in the class' constructor. Something like this:
class Foo {
protected static $someStr = 'bar';
private static $arr = [
'some_key' => [1]
];
public function __constructor()
{
self::arr['another_key'] = [2 => self::$somStr];
}
}
For this to work you will need to instantiate your class.
You can view some examples on property declarations in the PHP documentation.

Parent's class static variable different value for child's classes

Please, sorry for my English.
My problem:
abstract class Entity
{
protected static $fieldNames;
public static function getFieldsNames()
{
if (is_null(static::$fieldNames)) {
foreach (static::$fieldsMap as $name => $map) {
static::$fieldNames[] = $name;
}
}
return static::$fieldNames;
}
}
class User extends Entity
{
protected static $fieldsMap = [
'id' => [
// ...
],
'name' => [
// ...
],
'phone' => [
// ...
]
];
}
class Car extends Entity
{
protected static $fieldsMap = [
'id' => [
// ...
],
'brand' => [
// ...
],
'color' => [
// ...
]
];
}
print_r(User::getFieldsNames());
// ['id', 'name', 'phone'] - On first call it works as expected, but...
print_r(Car::getFieldsNames());
// ['id', 'name', 'phone'] :(
If I declare $fieldNames in User and Car classes work fine, but in real project I has tens of static variables such $fieldNames and hundreds of entity's
Is it possible to best solution?
Maybe create small repository class that will keep these static variables by entity's id? or another elegant way?
Thanks any Help!
$fieldNames is static so it's associated with the class itself and not with a specific object.
The class in this instance is "Entity".
Once you set it it is no longer null.

Extending Config breaks application

Here is my code:
// Yoda namespace
namespace Yoda\Application\Config\Feature;
// use zend config
use Zend\Config\Config;
// CacheConfig class
class CacheConfig extends Config
{
/**
* Default cache type for now
*
* #var string
*/
const DEFAULT_CACHE_TYPE = 'filesystem';
/**
* Default cache ttl for now
*
* #var integer
*/
const DEFAULT_CACHE_TTL = 3600;
/**
* Constructor. Creates config data for caching
*/
public function __construct()
{
$config=[
'name'=> static::DEFAULT_CACHE_TYPE,
'options' => [
'ttl' => static::DEFAULT_CACHE_TTL,
'cache_dir' => '/var/www/html/yoda/data/cache'
]
];
parent::__construct($config,true);
}
}
When I use this code the application breaks and says The localhost page isn't working however when I just pass the config array into a standard Zend Config object it works fine.
Here's my usage code:
$config=[
'name'=> 'filesystem',
'options' => [
'ttl' => 3600,
'cache_dir' => '/var/www/html/yoda/data/cache'
]
];
//works fine
$configCache = new Config($config);
//breaks
$configCache = new CacheConfig();
Not sure whats wrong here.
It's because in the Config class the constructor loads a static instance of itself. WHen I did this:
public function __construct()
{
$config=[
'name'=> static::DEFAULT_CACHE_TYPE,
'options' => [
'ttl' => static::DEFAULT_CACHE_TTL,
'cache_dir' => yoda::registry('cache_dir')
]
];
$this->allowModifications = true;
foreach ($config as $key => $value) {
if (is_array($value)) {
$this->data[$key] = new Config($value, $this->allowModifications);
} else {
$this->data[$key] = $value;
}
}
}
It seems to work when I replace it with Config
Instead of modifying zend config class you can do following in your configCache constructor. When config class will call cache class with array you pass the control back to config class with received array. It will then set the config object properly.The error is because of Static Bindings.
/**
* Constructor. Creates config data for caching
*/
public function __construct( $arr = [])
{
$config=[
'name'=> static::DEFAULT_CACHE_TYPE,
'options' => [
'ttl' => static::DEFAULT_CACHE_TTL,
'cache_dir' => '/var/www/html/yoda/data/cache'
]
];
if (count($arr) > 0)
{
parent::__construct($arr,true);
}
else
{
parent::__construct($config,true);
}
}
$configCache = new CacheConfig();
print_r($configCache);

Syntax error when accessing static array with in class

public static $config = array(
'base_url' => '',
'environment' => '',
'database' => array(
'dbdriver' => '',
'dbhost' => '',
'dbname' => '',
'dbuser' => '',
'dbpass' => ''
),
I want to access the base_url key and assign it to a new static property $app but it is giving me syntax error of unexpected [
public static $app_path = self::config['base_url']; //unexpected [ error
You want to access variable so you have to add $.
self::$config['base_url']
Read some more about that here.
Unfortunately you can't assign any variable (even static) to other static property as you can see in linked manual page.
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
Read the manual:
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
Right here
And before you think this is a severe limitation, let me tell you why this is a blessed relief:
class Foo
{
public static $evil = array('bar' => 123);
public static $check = self::$evil['bar'];
}
Foo::$check;//all is well
But then, when you introduce late static binding (something we all love):
class Foo
{
public static $evil = array('bar' => 123);
public static $check = static::$evil['bar'];
}
class Bar extends Foo
{
public static $evil = 123;
}
Bar::$check;//OOOPS
TL;TR: statics are something like super-globals: you can initialize them with a constant expression, but they can't require state to be initialized, that would be inception madness
The way you've initilized your (static) properties, is not yet implemented in PHP
You can check this thread's explanation: https://stackoverflow.com/a/1633024/4098311
However, this is how i'm doing in my projects :
<?php
class YourClass {
public static $config = NULL;
public static $app_path = NULL;
public static $_INITIALIZED = FALSE;
public static init() {
if(!self::$_INITIALIZED) {
self::$config = array(
'base_url' => '',
'environment' => '',
'database' => array(
'dbdriver' => '',
'dbhost' => '',
'dbname' => '',
'dbuser' => '',
'dbpass' => ''
));
self::$app_path = self::config['base_url'];
self::$_INITIALIZED = TRUE;
}
}
// ....
// Your Stuf ...
// ....
}
YourClass::init();

CodeIgniter: blank page when a model contains a function

i'm using codeigniter for a website project. when i include a model, it will work as long as no function is implemented (except the constructor).
this configuration works:
class Xyz_model extends CI_Model {
function __construct() {
}
}
this doesn't:
class Xyz_model extends CI_Model {
function __construct() {
}
public function get_xyz() {
return [
"xy" => ["xy"],
"yz" => ["xy"],
"zz" => ["xy","zx","zy"]
];
}
}
there is not even an database access... and i have no clue why it is not working.
You are extending the core model class, but the child's constructor is being used in placed of the parents:
parent::__construct();
Add that to your models constructor.
use this
In model
class Xyz_model extends CI_Model {
function __construct() {
}
public function get_xyz() {
$array = array(
'xy' => 'xy',
'yz' => 'xy',
'zz' => array("xy","zx","zy")
);
return $array;
}
}
In controller
$new = $this->Xyz_model->get_xyz()
print_r($new);
so output will be
Array ( [xy] => xy [yz] => xy [zz] => Array ( [0] => xy [1] => zx [2] => zy ) )

Categories