Use global variables inside static php class - php

As I am new to php oop I have a question how do I use global variables inside a static class with out using the constructor? Or must I use in this case a constructor?
$varGlob = 'hello mars';
class statclass {
global $varglob;
protected static $newVar = $varglob;// not going to work
static public function outputfunc(){
return statClass::$newVar;
}
}

You don't use global variables in a PHP class, but static variables. Although this seems confusing, global's aren't meant to be used in object-oriented PHP, but rather 'normal' PHP, old style.
See: http://nl3.php.net/manual/en/language.oop5.static.php for more information.

As Gordon mentioned you should not make use of globals or the thing I suggested because that will break your OOP design. You actually should pass the value through constructor [That's why they are meant for ]
However, the below code solves your purpose by making use of named constant such as define , Sadly this is an ugly-way...
<?php
define("varGlob","hello");
class statclass
{
protected static $newVar = varGlob;
static public function outputfunc(){
return statClass::$newVar;
}
}
echo statclass::outputfunc(); //"prints" hello
Alternate way.. (Recommended)
<?php
class settings
{
# Populate all your variables that are to be used.
protected $var1='Variable1';
protected $var2='Variable2';
}
class yourclass extends settings
{
# All those variables used in the class `settings` can be accessed here.
public function disp()
{
echo $this->var1;
}
}
$yc = new yourclass;
$yc->disp(); //"prints" Variable1

Related

Why declare class' properties when constructor initialize this properties

Write what is best and why?
class Chat
{
private $_couleur;
private $_race;
function __construct($couleur, $race)
{
$this->_couleur = $couleur;
$this->_race = "$race";
}
public function getCouleur() {
return $this->_couleur;
}
}
Or
class Chat
{
function __construct($couleur, $race)
{
$this->_couleur = $couleur;
$this->_race = "$race";
}
public function getCouleur() {
return $this->_couleur;
}
}
Because $this->_couleur is initialized when the class is instancied, so declare the property directly in the class is useless, isn't ?
Declaring the variables at the top of your class is a very good practice, because it makes it clear to anyone that reads your code which properties the class has private and which properties the class has public.
In the second example your variables will be public because they're dynamically generated.
When your constructor would be much bigger it is a pain in the ass as developer to find out where your variables are introduced.
It is also good to set default values (if they are always the same) to the variables in the class as opposed to the constructor. It makes your code more readable and understandable.
First block of code is better from the second, But one thing in first block.
Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.
This code collected from php.net
<?php
class Test
{
private $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
private function bar()
{
echo 'Accessed the private method.';
}
public function baz(Test $other)
{
// We can change the private property:
$other->foo = 'hello';
var_dump($other->foo);
// We can also call the private method:
$other->bar();
}
}
$test = new Test('test');
$test->baz(new Test('other'));
?>
Output:
string(5) "hello"
Accessed the private method.
The first one is better. You are actually declaring your variables as private, giving them a meaningful scope. The second version is more error-prone.
Just wanted to add one simple benefit of declaring class properties: Any good IDE will parse and build a symbol table out of your declared class properties. So if you are writing a class and start typing $this->, a list of your declared properties will show up so you can easily select the one you want to use. If you create variables in your constructor without declaring them, your IDE won't be able to see them.

var inside var in oop php

Im just a biginner in object oriented programming and currently learning object oriented php and i have got a bit confused with including a variable inside a variable inside of a class, usually i would do something like:
$div_content="some content";
$div = '<div>'.$div_content.'</div>';
but when trying to do it like this, i get an error:
class SomeClass{
private $div_content ="some content";
public $div='<div>'.$div_content.'</div>';
function __construct(){
echo $this->div;
}
}
Can some one please help me understand what im doing wrong here?
thanks in advance.
function __construct(){
$this->div = '<div>'.$this->div_content.'</div>';
echo $this->div;
}
You can define only static values on declarations, use the __construct() for it
When defining properties on a class like that, you may only use a specific value. There can be no calculations or operations. For example, you can't have public $five = 2+3;, it won't work.
Instead, you can define these properties in the constructor of your function.
You should look into getter and setter methods. You just want to get something, so use a getter method for $div, called getDiv
class SomeClass{
private $div_content = "some content";
public function getDiv() {
return '<div>'.$this->div_content.'</div>';
}
function __construct(){
echo $this->getDiv();
}
}
Variables are treated slightly different in classes -- and a construction like yours or maja's --- if it works -- is bound to cause -- "problems"
Try something like this, instead:
class SomeClass{
private $div_content;
public $div;
function __construct($content){
$this->div_content = $content;
$this->makeDiv();
}
function makeDiv(){
echo "<div>".$this->div_content."</div>";
}
}
Of course, there are a dozen ways to do it, but I would advise you not to define the variables in the beginning.

OO PHP Accessing public variable from another class

I have a class like the following:
class game {
public $db;
public $check;
public $lang;
public function __construct() {
$this->check = new check();
$this->lang = DEFAULT_LANG;
if (isset($_GET['lang']) && !$this->check->isEmpty($_GET['lang']))
$this->lang = $_GET['lang'];
}
}
As you can see I have a public variable $lang that is also defined via the contructor.
The proble is that I want to access the result of this variable from other classes that are not directly related to this class, since I don't want to redeclare it for each different class.
So for example how can I call the result of that variable from another class, lets call it class Check ?
if you mark the public $lang; as static:
public static $lang;
you can access it via game::$lang;
if not static, you need to make an instance of game and directly access it:
$game = new game;
$game->lang;
static call inside of (current) class:
self::$lang;
late static bound call (to inherited static variable):
static::$lang;
call from child class to parent:
parent::$lang;
normal call inside of an instance (instance is when you use new Obj();):
$this->lang;
BTW:
variables defined by define('DEFAULT_LANG', 'en_EN'); are GLOBAL scope, mean, can access everywhere!
<?php
define('TEST', 'xxx');
class game {
public function __construct() {
echo TEST;
}
}
//prints 'xxx'
new game;
you can make it static variable, so you will be able to call it anytime anywhere, the diff is that instead of
$this->lang;
when editing it(Works inside class game only) you do :
self::$lang;
and when you call/edit it (Works everywhere) from anther class you do :
game::$lang
the idea of static class is that its exist only in one instance, so only one $lang exist in your program. but there is no need to load the whole class to get acsess to it.
How can I call the result of that variable from another class, lets call it class Check?
A variable doesn't have a result. If you mean to retrieve the state of that variable on a specific object $obj of class game then you can simply do:
$obj->lang
On a side note if $lang is publicly only read only you should protect it by defining it private or protected and create a getter method instead.
If you mean that you want to use the same variable name in another class I'd suggest you to consider inheritance:
class Check extends game { /* now Check has $lang */ }
but the variable of the two objects will be different.
Since the property is public, you can access it from outside the class as $objInstance->property. It doesn't matter if you're calling it from a function, procedural script, in another object. As long as you have the instance, you can call it's public property. Ex:
function foo($c) {
echo $c->lang;
}
foo($check);
Also, some advice on working with objects and such: It's considered better code if you don't create instances of objects in the other objects, but rather pass them in someway (either a setter method or through the constructor). This keeps the classes loosely coupled and results in code that is more reusable and easier to test. So:
class Game
{
...
public function __construct($check, $defaultLang, $get) {
$this->check = $check;
$this->lang = $defaultLang;
if (isset($get['lang']) && !$this->check->isEmpty($get['lang']))
$this->lang = $get['lang'];
}
...
$game = new Game(new Check(), DEFAULT_LANG, $_GET);
echo $game->check;
The first half of this article is an accessible explanation of what is known as Dependency Injection.

PHP Define Variable containing a Class

I'm attempting to define a __invokeable global instance of a class that contains my application's functions.
Basically I'm trying to create a namespace for my library, and therefore I'm attempting to use a class to hold all my functions/methods.
I don't want to have to include global $class_instance at the top of all my files, because that is ugly.
Also I don't to have to reference the variable like $GLOBALS['myvar'] everywhere.
Personally I find this a real oversight in php.
It appears I can't define super globals like $myFunctionsGlobal
And I can't define variables (well actually constants) in php like myvar=$classInstance.
Namespaces
If namespaces are supposed to solve this issue, why aren't they more widely used?
For example Kohana doesn't use namespaces, along with many other php libraries.
One I'm after:
class _namespace{
public $_function;
function __invoke($arg){
// Function body
echo $arg;
}
function method(){
;
}
}
$N = new _namespace;
$N('someValue');
$N->method();
function myFunc(){
// I don't want global $N;
// I don't want $N = $_GLOBALS['N'];
// I don't want $N = get_instance();
$N('some other value');
}
Solution:
In most other languages like c and js you can only have one object/function per variable name. PHP seems to special allowing you to have namespaces,functions and classes with the same name. I was trying to group all of my functions under one central variable for simplicity and still have the functionality of it being __invokable. In fact a class and a function named the same thing would have provided this functionality.
<?
class R{
static function static_method(){
;
}
function method(){
;
}
}
function R(){;}
R();
R::static_method();
$instance = new R();
$instance->method();
In php5.3 you can emulate a invokable constant with methods by defining a function with the same name as your namespace.
namespace.php
<? namespace Z;
function init($arg=''){
echo $arg;
}
function method(){
echo 'method';
}
function method(){
echo 'method2';
}
othefile.php
include('namespace.php');
function Z($a=null,$b=null){
return Z\init($a,$b);
}
Z('test');
Z\method();
Z\method2();
Here's my new answer for you it works
class _bidon {
static function __invoke($arg){
// Function body
echo $arg;
}
}
$b = new _bidon;
$b('eee');
function myFunc(){
// I don't want global $N;
// I don't want $N = $_GLOBALS['N'];
// I don't want $N = get_instance();
_bidon::__invoke('some other value');
}
myFunc();
but the function will be specific to the class not the object
------ Previous post :
Hi i did not clearly understand but if you have a class created just do :
public static $myFunctionsGlobal;
and whene you want to use it outer than your class you do :
myclassname::$myFunctionsGlobal
and it will be accessible as soon as you include your class
you don't need to create an object because it's a static var you just need to have the class included
You can use a service container.
An example you can find here: Which pattern should I use for my unique instance of the User class? and to deepen If Singletons are bad then why is a Service Container good?
Also namespaces can't help you if you need to have one single instance for your helper objects like you are asking.
Addendum
With the service container I suggest you can still use __invoke.
$obj = app('CallableClass');
$obj(5);

Can I make a variable globally visible without having to declare it global in every single PHP class's constructor?

I have a database class, which an instance is declared in the main index.php as
$db = new Database();
Is there a way for the $db variable to be globally recognized in all other classes without having to declare
global $db;
in the constructor of each class?
No. You have to declare Global $db in the constructor of every class.
or you can use the Global array: $_GLOBALS['vars'];
The only way to get around this is to use a static class to wrap it, called the Singleton Method (See Here for an explanation). But this is very bad practice.
class myClass
{
static $class = false;
static function get_connection()
{
if(self::$class == false)
{
self::$class = new myClass;
}
else
{
return self::$class;
}
}
// Then create regular class functions.
}
The singleton method was created to make sure there was only one instance of any class. But, because people use it as a way to shortcut globalling, it becomes known as lazy/bad programming.
StackOverflow Knowledge
How to Avoid Using PHP Global Objects
Share Variables Between Functions in PHP Without Using Globals
Making a Global Variable Accessible For Every Function inside a Class
Global or Singleton for Database Connection
I do it a little different. I usually have a global application object (App). Within that object I do some basic initialization like creating my db objects, caching objects, etc.
I also have a global function that returns the App object....thus (application object definition not shown):
define('APPLICATION_ID', 'myApplication');
${APPLICATION_ID} = new App;
function app() {
return $GLOBALS[APPLICATION_ID];
}
So then I can use something like the following anywhere in any code to reference objects within the global object:
app()->db->read($statement);
app()->cache->get($cacheKey);
app()->debug->set($message);
app()->user->getInfo();
It's not perfect but I find it to make things easier in many circumstances.
you could use
$GLOBALS['db']->doStuff();
or alternatively using some kind of singleton access method
Database::getInstance()->doStuff();
Why not create a class that contains the global $db; in it's constructor, then extend all other classes from this?
You could use a Registry class to store and retrieve your Database instance.
class Registry
{
protected static $_data = array();
public static function set($key, $value)
{
self::$_data[$key] = $value;
}
public static function get($key, $default = null)
{
if (array_key_exists($key, self::$_data)) {
return self::$_data[$key];
}
return $default;
}
}
Registry::set('db', new Database());
$db = Registry::get('db');

Categories