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();
Related
I have created a trait in Laravel.
In myconstruct I am calling a setting('value') - This is provided by the qcod/laravel-app-settings package.
But inside my methods when I reference $this->token or $this->org_id it returns NULL
I know the values are set, as they're showing in the config and are also set correctly in the Database.
My PHP code is :
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Log;
trait PropertyBaseTrait
{
private $org_id;
private $token;
private $is_set;
public function __construct()
{
$this->org_id = setting('propertybase_org');
$this->token = setting('propertybase_token');
}
public function base_url($method)
{
return 'https://pb-integrations-api-staging.herokuapp.com/api/v1/'.$method.'/'.$this->org_id.'';
}
public function post_lead($data)
{
$lead_data = array(
'first_name' => '',
'last_name' => '',
'email' => '',
'phone1' => '',
'phone2' => '',
'phone3' => '',
'address' => '',
'city' => '',
'state' => '',
'zip_code' => '',
'country_name' => '',
'landing_page' => '',
'search_term' => '',
'referral_source' => ''
);
$object_type = 'lead';
$action_type = 'create';
dd($this->token);
$endpoint = $this->base_url('messages');
$this->post_data( $endpoint, $object_type, $action_type, json_encode($data));
}
The problem is that you have construct in your trait and maybe in your class where you are using this trait.
possible scenario:
class MyClass {
use MyTraitWithConstructor;
public function __construct(){
...
}
}
In this case trait constructor doesn't work.
What You can do?
You can rename trait construcor like this:
class MyClass {
use PropertyBaseTrait {
PropertyBaseTrait::__construct as private __prConstruct;
}
public function __construct(){
$this->__prConstruct();
...
}
}
Avoid writing constructor in traits. That's what I can say.
Instead, you can make them as normal method, then just call it in your class constructor.
Trait
trait Bar
{
public function init()
{
$this->org_id = setting('propertybase_org');
$this->token = setting('propertybase_token');
}
}
Class
class Foo
{
use Bar;
public function __construct()
{
$this->init();
}
}
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.
after creating inside setUp() two variables, i cant figure out how should i pass them to second function and use them.
this is my last attempt:
class adRequestTest extends PHPUnit_Framework_TestCase{
protected function setUp(){
$env = \Slim\Environment::mock([
'REQUEST_METHOD' => 'PUT',
'REQUEST_URI' => '/foo/bar',
'QUERY_STRING' => 'abc=123&foo=bar',
'SERVER_NAME' => 'example.com',
'CONTENT_TYPE' => 'application/json;charset=utf8',
'CONTENT_LENGTH' => 15
]);
$request = new \Slim\Http\Request($env);
}
function testInitFromHttpRequest_correctConstruction($request, $env){
$fixture = new AdRequest();
$fixture->initFromHttpRequest($request, $env);
}
}
i tried doing that by passing them like this as well :
function testInitFromHttpRequest_correctConstruction($request = $this->request, $env = $this->env)
but didnt work as well.
i am getting this error:
Missing argument 1 for adRequestTest::testInitFromHttpRequest_correctConstruction()
but i am passing two arguments like defined in the declaration... what am i missing here?? thx
The PHPunit framework don't pass any arguments to your function until you don't define a dataprovider (is not your case/scenario).
You can try this modified test case that define as class scope the variable you define in the setup method:
class adRequestTest extends PHPUnit_Framework_TestCase{
private $env;
private $request;
protected function setUp(){
$this->env = \Slim\Environment::mock([
'REQUEST_METHOD' => 'PUT',
'REQUEST_URI' => '/foo/bar',
'QUERY_STRING' => 'abc=123&foo=bar',
'SERVER_NAME' => 'example.com',
'CONTENT_TYPE' => 'application/json;charset=utf8',
'CONTENT_LENGTH' => 15
]);
$this->request = new \Slim\Http\Request($this->env);
}
function testInitFromHttpRequest_correctConstruction(){
$fixture = new AdRequest();
$fixture->initFromHttpRequest($this->request, $this->env);
// write here your tests/assertions...
}
}
Hope this help
i have multiple php classes
// a Base class
abstract class Base_Page {
protected static $config = array(
'status' => 'int',
);
}
// an inheriting class
class Page extends Base_Page{
protected static $config = array(
'title' => 'varchar',
'description' => 'text',
);
// and one more level of inheritance
class Page_Redirect extends Base_Page {
protected static $config = array(
'href' => 'http://domain.com',
);
}
now id'd like to do this:
$page_redirect = new Page_Redirect();
$page_redirect->getConfig(); // which i assume to be implemented (this is my problem)
// should return:
// array(
// 'status' => 'int',
// 'title' => 'varchar',
// 'description' => 'text',
// 'href' => 'http://domain.com',
// )
Due to the fact that the variable gets overwrote by the extending class a dont't get how to accomplish this. Thanks for your look at it.
You cannot do this with a bare property. It would be much better to use methods instead:
abstract class Base_Page {
protected function getConfig() {
return array('status' => 'int');
}
}
// an inheriting class
class Page extends Base_Page{
protected function getConfig() {
return array(
'title' => 'varchar',
'description' => 'text',
) + parent::getConfig();
}
}
// and one more level of inheritance
class Page_Redirect extends Base_Page {
protected function getConfig() {
return array(
'href' => 'http://domain.com',
) + parent::getConfig();
}
}
Of course now you have lost the ability to get the configuration statically, but it's highly likely that this does not matter. If it does (i.e. you need to know the configuration without having an instance at hand, and it is meaningless to create one on a whim) then the code needs further refactoring.
<?php
// a Base class
abstract class Base_Page {
protected static $config = array(
'status' => 'int',
);
}
// an inheriting class
class Page extends Base_Page {
protected static $config = array_merge(
parent::$config,
array(
'title' => 'varchar',
'description' => 'text',
)
);
}
Try something like this.
The purpose of this code is just separate the config data. If i use the $config array directly in the example.php all works properly. However in the code below i get different values.
facebook.php
<?php
class Facebook extends AppController{
public function __construct() {
$config = array();
$config['appId'] = '400xxx6'; //YOUR_APP_ID
$config['secret'] = 'f70f01e76xxx7e'; //YOUR_APP_SECRET
$config['cookie'] = false;
return $config;
}
}
?>
example.php
<?php
App::import('Config', 'Facebook');
$a = new Facebook();
var_dump($a);
?>
Why $var_dump($a); return something like this?
object(Facebook)[50]
protected 'appId' => null
protected 'apiSecret' => null
protected 'user' => null
protected 'signedRequest' => null
protected 'state' => string 'e4ac55f1xxx87a88' (length=32)
protected 'accessToken' => null
protected 'fileUploadSupport' => boolean false
What I want is the original array. What is the mistake?
array
'appId' => string '400xxx6' (length=15)
'secret' => string 'f70f01e76xxx7e' (length=32)
'cookie' => boolean false
I'm pretty sure that when you do:
$a = new Facebook();
the class being instantiated is not the one you created. I believe you use Facebook PHP SDK, and their class name is also Facebook. You have conflicting class names.
Change your class name for something else like FacebookConfig and you'll be fine.
Also, it would make more sense to store your array in the class instance, something like:
class FacebookConfig extends AppController{
public $config = array();
public function __construct() {
$this->config = array();
$this->config['appId'] = '400xxx6'; //YOUR_APP_ID
$this->config['secret'] = 'f70f01e76xxx7e'; //YOUR_APP_SECRET
$this->config['cookie'] = false;
}
}