PHP How to use class instance inside method - php

How can I use class instance inside independent method?
I some file have:
global $l;
$l = new l('bg');
include('second.php');
In second.php I have:
function a() {
print_r($l);
}
$l is coming like NULL;
class l declaration:
class l {
var $lang = array();
function l($lang) {
}
function g($string) {
}
}
My question - how can I use $l instance inside of my function a.
Thanks.

In function a $l is not defined.
Either you pass it in as a parameter or you use global.
function a($l) {
print_r($l);
}
global is not like var. It does not define a variable to be used as a global. Instead, global allows you to pull variables from the global scope, like:
$l = new l();
function a() {
global $l;
print_r($l);
}
I should also add that the use of global is heavily frowned upon, it breaks dependency expectations. This means that if you look at your function a you can't see that it needs $l. If it's a parameter then you know it needs $l.

Related

PHP assign a value to a variable (globa) from within the classs

I have a small PHP snippet.
How can I assign a new value to my global from within a main class?
Example:
$GlobalValue = 0;
class SampleModuleController extends SampleController {
public function doSomething() {
$NewValue = 1;
$GlobalValue = $NewValue
}
}
echo $GlobalValue;
//This always echo's 0, When I try to output or print outside the class or use somewhere above in the php code.
//I need to be able to assign the new value from within my class
//and the function doSomething so it should be 1
You can pass parameter as reference in the method doSomething() and then call that function passing your variable $GlobalValue. However it's not very recommended to have global variables. You should consider change your code to more OOP.
$GlobalValue = 0;
class SampleModuleController {
private $newValue = 3;
public function doSomething(&$variable) {
$variable = $this->newValue;
}
}
$ModuleController = new SampleModuleController();
$ModuleController->doSomething($GlobalValue);
echo $GlobalValue; //print 1
If i understood it right what you are trying to do can be achieved quite easily with this:
global $GlobalValue;
$GlobalValue = 0;
class SampleModuleController {
public function doSomething() {
global $GlobalValue;
$NewValue = 1;
$GlobalValue = $NewValue;
}
}
$ModuleController = new SampleModuleController();
$ModuleController->doSomething();
echo $GlobalValue; //print 1
They key is in the "global" keyword (which is the same as accessing the $GLOBAL["your_var_name"] container.
Beside this, as others said relying on global variables should be discouraged.

PHP encapsulation without class?

Is it possible to encapsulate, a variable or function let say, in PHP without wrapping them in a class? What I was doing is:
//Include the file containing the class which contains the variable or function
include('SomePage.php');
//Instantiate the class from "SomePage.php"
$NewObject = new SomeClassFromSomePage();
//Use the function or variable
echo $NewObject->SomeFuncFromSomeClass();
echo $NewObject->SomeVarFromSomeClass;
My intention is to avoid naming conflict. This routine, although it works, makes me tired. If I cannot do it without class, it is possible not to instantiate a class? and just use the variable or function instantly?
To use class methods and variables without instantiating, they must be declared static:
class My_Class
{
public static $var = 123;
public static function getVar() {
return self::var;
}
}
// Call as:
My_Class::getVar();
// or access the variable directly:
My_Class::$var;
With PHP 5.3, you can also use namespaces
namespace YourNamespace;
function yourFunction() {
// do something...
}
// While in the same namespace, call as
yourFunction();
// From a different namespace, call as
YourNamespace\yourFunction();
PHP Namespaces were made to archive the exact same goal:
<?php // foo.php
namespace Foo;
function bar() {}
class baz {
static $qux;
}
?>
When using call namespaced functions like this:
<?php //bar.php
include 'foo.php';
Foo\bar();
Foo\baz::$qux = 1;
?>
This is a way to encapsulate without Class
<?php
(function (){
$xyz = 'XYZ';
})();
echo $xyz; // warning: undefined
Encapsulation Alternative
With this method you can minimize unintentional using array key(uses it instead of variables). Can also use value stored in array anywhere after assigning. Shorter array key area length with variable in keys, inside encapsulation function; outside encapsulation function, variables can be used in keys but otherwise long discriptive keys. Nested encapsulation can also be used.
Example
<?php
define('APP', 'woi49f25gtx');
(function () {
$pre = 'functions__math__'; // "functions" is main category, "math" is sub.
$GLOBALS[APP][$pre . 'allowedNumbers'] = [3,5,6];
$GLOBALS[APP][$pre . 'square'] = function ($num) {
return $num * $num;
};
$GLOBALS[APP][$pre . 'myMathFunction'] = function ($num) use ($pre) {
if(in_array($num,$GLOBALS[APP][$pre . 'allowedNumbers'])) return 'not allowed';
return $GLOBALS[APP][$pre . 'square']($num);
};
})();
echo $GLOBALS[APP]['functions__math__myMathFunction'](4);

PHP closure scope problem

Apparently $pid is out of scope here. Shouldn't it be "closed" in with the function? I'm fairly sure that is how closures work in javascript for example.
According to some articles php closures are broken, so I cannot access this?
So how can $pid be accessed from this closure function?
class MyClass {
static function getHdvdsCol($pid) {
$col = new PointColumn();
$col->key = $pid;
$col->parser = function($row) {
print $pid; // Undefined variable: pid
};
return $col;
}
}
$func = MyClass::getHdvdsCol(45);
call_user_func($func, $row);
Edit I have gotten around it with use: $col->parser = function($row) use($pid). However I feel this is ugly.
You need to specify which variables should be closed in this way:
function($row) use ($pid) { ... }
You can use the bindTo method.
class MyClass {
static function getHdvdsCol($pid) {
$col = new PointColumn();
$col->key = $pid;
$parser = function($row) {
print $this->key;
};
$col->parser = $parser->bindTo($parser, $parser);
return $col;
}
}
$func = MyClass::getHdvdsCol(45);
call_user_func($func, $row);
I think PHP is very consistent in scoping of variables. The rule is, if a variable is defined outside a function, you must specify it explicitly. For lexical scope 'use' is used, for globals 'global' is used.
For example, you can't also use a global variable directly:
$n = 5;
function f()
{
echo $n; // Undefined variable
}
You must use the global keyword:
$n = 5;
function f()
{
global $n;
echo $n;
}

Using Global Variable [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
To pass value of a variable in one function to another function in same class
Can a value of a variable in one function be made available in another function on the same class using "GLOBAL" in PHP. If so please suggest how can this be achieved using Global.
You don't need to make a variable GLOBAL if you're within an object.
class myClass {
public $myVar = "Hello";
function myFunction() {
echo $this->$myVar;
}
}
This is one of the main points of objects - that you can assign different values to variables and get/set those variables within the different methods. And also that you can create multiple instances of objects each holding different information within the same structure and with the same methods available.
Additionally to what #Codecraft said (about using public properties), you can use:
indeed global variable (which is really something you should avoid doing),
passing values in parameters,
static variable within class,
Below is the example of using static variable (private), because I think this suits your needs best:
class MyClass {
private static $_something;
public function write() {
static::$_something = 'ok';
}
public function read() {
return static::$_something;
}
}
$x = new MyClass();
$x->write();
var_dump($x->read());
which outputs:
string(2) "ok"
This is in fact something like a global, but available only from inside your class (because of the keyword "private") and common among every instance of the class. If you use setting some non-static property, it will change across different instances of the class (one object may have different value stored in it than the other object has).
Comparison of solutions based on static and non-static variables:
Solution based on static variable will give you really global-like behaviour (value passed across different instances of the same class):
class MyClass {
private static $_something;
public function write() {
static::$_something = 'ok';
}
public function read() {
return static::$_something;
}
}
// first instance
$x = new MyClass();
$x->write();
// second instance
$y = new MyClass();
var_dump($y->read());
which outputs:
string(2) "ok"
And the solution based on non-static variables will look like:
class MyClass {
private $_something;
public function write() {
$this->_something = 'ok';
}
public function read() {
return $this->_something;
}
}
// first instance
$x = new MyClass();
$x->write();
// second instance
$y = new MyClass();
var_dump($y->read());
but will output:
NULL
which means that in this case the second instance has no value assigned for the variable you wanted to behave like "global".
Yes, a value of a variable in one function can be made available in another function on the same class using "GLOBAL". The following code prints 3:
class Foo
{
public function f1($arg) {
GLOBAL $x;
$x = $arg;
}
public function f2() {
GLOBAL $x;
return $x;
}
}
$foo = new Foo;
$foo->f1(3);
echo $foo->f2();
However, the usage of global variables is usually a sign of poor design.
Note that while keywords in PHP are case-insensitive, it is custom to use lower case letters for them. Not also that the superglobal array that contains all global variables is called $GLOBALS, not GLOBAL.

PHP access external $var from within a class function

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like
class myclass {
bla ....
bla ....
function myfunction() {
if (isset($some_external_var)) do something ...
}
}
$some_external_var =true;
$obj = new myclass();
$obj->myfunction();
Thanks
You'll need to use the global keyword inside your function, to make your external variable visible to that function.
For instance :
$my_var_2 = 'glop';
function test_2()
{
global $my_var_2;
var_dump($my_var_2); // string 'glop' (length=4)
}
test_2();
You could also use the $GLOBALS array, which is always visible, even inside functions.
But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !
A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
Global $some_external_var;
function myfunction() {
Global $some_external_var;
if (!empty($some_external_var)) do something ...
}
}
But because Global automatically sets it, check if it isn't empty.
that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.
Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?
Use Setters and Getters or maybe a centralized config like:
function config()
{
static $data;
if(!isset($data))
{
$data = new stdClass();
}
return $data;
}
class myClass
{
public function myFunction()
{
echo "config()->myConfigVar: " . config()->myConfigVar;
}
}
and the use it:
config()->myConfigVar = "Hello world";
$myClass = new myClass();
$myClass->myFunction();
http://www.evanbot.com/article/universally-accessible-data-php/24

Categories