Cannot access to changed property - php

I've created a class called Boot, inside this I've a method that change the path of a file, so the user can call it to set a custom path, something like this:
class Boot
{
private static $_filePath = 'directory/';
public function __construct()
{
require 'system.php';
}
public function init()
{
new System();
}
public function setFilePath($newDir)
{
$this->_filePath = $newDir;
}
public static function getFilePath()
{
return self::_filePath;
}
}
so in my index.php file:
require 'boot.php';
$b = new Boot();
$b->setFilePath('directories/');
$b->init();
Now in the system class I call something like this:
echo Boot::getFilePath();
and should be displayed directories/ but I see again the default value: directory.
Now I though that this issue is related to the static field, but how can I access to the changed value so? Thanks.

Class variables defined with and without static are different variables.
One solution is to remove static from variable declaration and change getPath code, as you already have instance of Boot defined witn new:
class Boot
{
private $_filePath = 'directory/';
public function __construct()
{
require 'system.php';
}
public function init()
{
new System();
}
public function setFilePath($newDir)
{
$this->_filePath = $newDir;
}
public function getFilePath()
{
return $this->_filePath;
}
}
And call getFilePath() as
echo $b->getFilePath();
Another solution is to change both setFilePath and getFilePath:
public function setFilePath($newDir)
{
// set STATIC variable
self::$_filePath = $newDir;
}
public static function getFilePath()
{
// get STATIC variable
return self::$_filePath;
}
But in the end it's a bad approach because you will make mistakes deciding whether you need to access a static variable or a property of an object.
So it's better to make a decision - either you have an instance of Boot and get properties of it or you have only static methods in a class and forget about Boot instance.

Related

Can't access construct variable in method ( php laravel )

I have a base class which sets up's other extending controllers like this:
class BaseController extends Controller
{
public $globalCurrencies;
public $globalLanguages;
public function __construct()
{
$this->globalCurrencies = $this->getCurrencies(); // this works
$this->globalLanguages = $this->getLanguages(); // this works
}
}
And I use one of helpers to extend this class like this:
class SessionHelper extends BaseController
{
public $test;
public function __construct()
{
parent::__construct(); // fire parent aka basecontroller construct
$this->test = $this->globalCurrencies; // this works (variables are set)
echo '__construct: '.$this->test; // this even displays it
}
public function getCurrencies()
{
dd('method'.$this->test); // NOT WORKING
}
public function getCurrentCurrency()
{
return $this->getCurrencies()->where('id', Session::get('currencyId'))->first() ?? null;
}
}
Later on code is used in model:
class Product extends Model
{
protected $table = "products";
public $timestamps = true;
public $sessionHelper;
public function __construct()
{
$this->sessionHelper = new SessionHelper;
}
public function getPrice($conversion_rate = null)
{
return number_format($this->price_retail / $this->sessionHelper->getCurrentCurrency()->conversion_rate, 2);
}
}
Have any body idea why I can access in construct variable but not in method? If i remember correctly construct is fired first so everything after should have access to it.
Declare $test variable as private out side the constructor. Inside the constructor keep it the way you are doing it right now and then make a setter and getter for the test variable.
class testObject
{
private $test;
function __construct($test)
{
$this->test= $this->globalCurrencies;
}
// test getter
function getTest()
{
return $this->test;
}
}
Change your method to be;
public function getCurrencies()
{
dd('method', $this->test);
}
You can not concatenate strings and objects/arrays.
If that doesn't resolve the issue - check the laravel.log

How can I limit the scope of a variable to a single file?

I have several functions which share common variables. But I don't want to keep passing these variables between all the functions, because that means all functions will have a lot of parameters and I find that hard to read.
So I want to define 'global' variables only for these functions, something like so:
$varA;
$varB;
$varC;
function funcA() {
..
}
function funcB() {
..
}
function funcC() {
..
}
As opposed to the ugly way of funcA declaring the variables and functions passing them around between them (resulting in many parameters for each function).
However I want the variables to not be global to all files in the program. Only accessible in this file.
What is the best or most common way to achieve something like this?
If you don't really want to build objects, but only want to have a private scope, you could use static class:
<?php
class Example {
private static $shared_variable;
/* disable the constructor to create a static class */
private function __construct() {}
static function funcA() {
self::$shared_variable = 'AVAILABLE HERE';
}
static function funcB() {
echo self::$shared_variable;
}
}
Example::funcA();
Example::funcB();
// echo Example::$shared_variable; // but not here
I added the private delaration of constructor to prevent the object creation (thus declaring the class static).
I would create a class and refactor the functions to methods and the variables to parameters:
Class newClass
{
private $varA;
private $varB;
private $varC;
public function funcA()
{
$varB = $this->varB;
}
public function funcB()
{
$varC = $this->varC;
}
public function funcC()
{
$varA = $this->varA;
}
}
This way you will have full access to all the set parameters in all your subsequent methods. You can write a setter or create a constructor to add a value to your parameters:
Class newClass
{
public function __construct($varA, $varB, $varC)
{
$this->varA = $varA;
$this->varB = $varB;
$this->varC = $varC;
}
}
This is how I would handle the local scope. Good luck!
The proper way of encapsulating variables and functions which depends on these variables is by using a class.
class MyClass
{
private $varA;
private $varB;
private $varC;
public function __construct($varA, $varB, $varC)
{
$this->varA = $varA;
$this->varB = $varB;
$this->varC = $varC;
}
public function funcA()
{
$localVarB = $this->varB;
}
public function funcB()
{
$localVarC = $this->varC;
}
public function funcC()
{
$localVarA = $this->varA;
}
}
To use this class you must first create an instance of it:
$classInstance = new MyClass("varA", "varB", "value");
$classInstance->funcA();
$classInstance->funcB();
...
More information about classes in php can be found here: http://php.net/manual/en/keyword.class.php

Php get variable from required file

I have a class:
class My_Class {
private $playlist_table_name;
public function __construct() {
$this->playlist_table_name = "something";
require_once('markup.php');
}
}
How do I access $playlist_table_name from markup.php file?
I tried using: $this->playlist_table_name, but I get:
Using $this when not in object context
If you want to access the variable like that, you will need to mark it as public
class My_Class {
public $playlist_table_name;
public function __construct() {
$this->playlist_table_name = "something";
require_once('markup.php');
}
}
You are then going to want to instantiate the class before attempting to use it.
$MyClass = new My_Class;
echo $MyClass->playlist_table_name;
That will allow you to echo out the value.

Overwrite a static method with a non static method

I want to overwrite a static method with a non static method. I'm getting this error:
Fatal error: Cannot make static method Person::say() non static in class Coder on line 22
I want to overwrite a classes parent static method makeCall() with a more specific makeCall() that would be non-static.
Code:
<?php
class Request {
public static function makeCall($url) {
// Do some cURL stuff...
}
}
class API extends Request {
const PRODUCTS = '/products';
private $api;
public function __construct($api) {
$this->api = $api;
}
public function getProducts() {
$this->makeCall(self::PRODUCTS);
}
public function makeCall($service) {
parent::makeCall($this->api . $service);
}
}
I could make the parent makeCall() non-static, but I also want to be able to Request:makeCall() in some places.
You may simply change your methods name. And call it with the new name.
There is no option to have it the same name as a static method of the class you're extending.

Static methods requiring var

Ok, i'm stuck on this, why don't i get what i need?
class config
{
private $config;
# Load configurations
public function __construct()
{
loadConfig('site'); // load a file with $cf in it
loadConfig('database'); // load another file with $cf in it
$this->config = $cf; // $cf is an array
unset($cf);
}
# Get a configuration
public static function get($tag, $name)
{
return $this->config[$tag][$name];
}
}
I'm getting this:
Fatal error: Using $this when not in object context in [this file] on line 22 [return $this->config[$tag][$name];]
And i need to call the method in this way: config::get()...
public static function get
need to be
public function get
You can't use $this in static methods.
EDITED
I could do this, but I'm not sure if it's the best design for you.
class config
{
static private $config = null;
# Load configurations
private static function loadConfig()
{
if(null === self::$config)
{
loadConfig('site'); // load a file with $cf in it
loadConfig('database'); // load another file with $cf in it
self::$config = $cf; // $cf is an array
}
}
# Get a configuration
public static function get($tag, $name)
{
self::loadConfig();
return self::$config[$tag][$name];
}
}
The problem is that you're Using $this when not in object context... Declaring a method as static removes the possibility to use the $this-reference inside the method.
There is no $this reference inside static methods as they belong to the class. Static methods can only access static members, so if it is important that get() is a static method, make $this->config a static member and return self::$config[$tag][$name]. However, the static keyword makes methods accessible without an instance of the class and I'd advise either making get() non-static, or making the class a singleton (depending on how you wish to use it).

Categories