I need to pass a variable from a static function to another within the same class.
I do not write the full code, I need the theoretical procedure
enter code here
class One
{
public static function One()
{
/**
* some code extract from DB $one
*/
}
public static function two()
{
/**
* I need to retrieve the variable $one to use it in another query DB
*/
}
}
Note:
you can't use $this in a static function
Declare $one as a static variable:
private static $one;
And you can access it using : self::$one
You need to declare your variable within your One class, then you can retrieve it using self and the scope resolution operator ::.
class One {
private static $one;
public static function One() {
self::$one = something_from_your_db();
}
public static function two() {
do_something(self::$one);
}
}
Related
I'am trying to make a reference to a static function inside a class:
class Test {
function __construct() {
$this->fn1 = self::fn2;
}
public static function fn2() {
}
}
then i get this error:
Undefined class constant 'fn2'
why?
Not sure if this is what you want, but at least this might give you a hint:
<?php
class Test {
function __construct() {
$this->fn = function(){
return self::realFn();
};
}
public function callFn (){
$fn = $this->fn ;//yes, assigning to a var first is needed. You could also use call_user_func
$fn();
}
public static function realFn() {
echo 'blah';
}
}
$x = new Test();
$x->callFn();
You can test it here: https://3v4l.org/KVohi
You have defined a static function:
Test {
function__construct()
{
$this->fn1 = self::fn2();
}
public static function fn2()
{
}
}
Updated
If you want to assign a function to a variable, it is best to do this
with annonymous aka lambda functions since they are first class citizens and may be freely passed, returned and assigned. PHP is not unique in dealing with static method references in this fashion as JAVA implements them similarly:
Method references ... are compact, easy-to-read lambda expressions for
methods that already have a name.
You may create an anonymous function based on a callable in PHP, and so the OP may wish to do as follows, which PHP 7.1.10 or higher supports:
<?php
class Test {
public static function fn2() {
return __METHOD__;
}
public static function getClosure (){
return Closure::fromCallable(["Test","fn2"]);
}
}
echo Test::getClosure()(),"\n";
See live code here
In this example an anonymous function is created and returned by the static getClosure method. When one invokes this method, then it returns the closure whose content is the same as static method fn2. Next, the returned closure gets invoked which causes the name of static method fn2 to display.
For more info re closures from callables, see the Manual and the RFC.
With PHP 7 on up, you may create a complex callable. In the code below the complex callable is an invocable array:
<?php
class foo
{
public static function test()
{
return [__CLASS__, 'fn2'];
}
public static function fn2()
{
echo __METHOD__;
}
}
echo foo::test()();
See live code.
Note: Starting with PHP 7.0.23 you could create a complex callable using a string containing the class and method names separated by the double colon aka paaamayim nekudotayim; see here.
A solution that has broader PHP support is as follows:
<?php
class Test {
public static function fn2() {
return __METHOD__;
}
public static function tryme(){
return call_user_func(["Test","fn2"]);
}
}
// return closure and execute it
echo Test::tryme();
See live code
I have a code here,
class someClass {
public $someMember;
public function __construct() {
$this->someMember = 1;
}
public static function getsomethingstatic() {
return $this->someMember * 5;
}
}
$obj = new someClass();
echo $obj::getsomethingstatic();
and return an error, I know it has something to do with static but I couldn't find good explanation. I know how to fix this, I'm just looking for an explanation which will add to my understanding.
Anyone?
A static function ($obj::) cannot return/use a non-static ($this) class property, you'd have to make getsomethingstatic non-static to return the variable or make the variable static and update your other functions respectively.
As $this refers to the instance in question and static functions by definition are used outside of the instance it is not possible to mix.
ProTip
In the future, please include the error in the OP. It was easy to spot the error in this question but it might not have been in another case so included the required information speeds up the process.
You don't use the object accessor -> within Static methods. Use the Scope-Resolution Operator :: instead; prefixing it with either self or static as shown below. However be sure to use only static member variables/properties within Static methods as well...
class someClass {
public static $someMember;
public function __construct() {
self::$someMember = 1;
// OR
static::$someMember = 1;
}
public static function getsomethingstatic() {
return self::$someMember * 5;
// OR
return static::$someMember * 5;
}
}
// TO CALL A STATIC METHOD OF A CLASS,
// YOU NEED NOT INSTANTIATE THE CLASS...
// SIMPLY CALL THE METHOD DIRECTLY ON THE CLASS ITSELF....
echo someClass::getsomethingstatic();
class Exam {
public $foo = 1;
public static function increaseFoo(){
$this->foo++;
echo $this->foo;
}
}
Exam::increaseFoo();
This code generate an Error
E_ERROR : type 1 -- Using $this when not in object context -- at line 5
Is that possible to use global variable into static mathod?
replace $this with self, also you must mark your variable as static when using it in a static method:
class Exam {
public static $foo = 1;
public static function increaseFoo(){
self::$foo++;
echo self::$foo;
}
}
Exam::increaseFoo();
Variable inside class has to be static. No need to declare the variable as public.
class Exam {
private static $foo = 1;
public static function increaseFoo(){
self::$foo++;
echo self::$foo;
}
}
Exam::increaseFoo();
Firstly, Variable needs to be static as the method where you want to use this variable is static method
Secondly, need to use self:: instead of $this-> while refferencing the class
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
I have a class Blocka_Model (actually a MODEL in KOhana framework) with 2 functions input() and output().The function input is called from a function wriiten inside a controller called Home_Controller and it passes an argument to the function input. Now I want that argument passed to input() function to be accessible in the function output(). Both the functions input() and output() are inside Model class Blocka_Model. I want to get that argument $val from input() to output)
class Blocka_Model extends Block_Model {
protected $tablname = 'moves';
public function input($val) { ... }
public function output() { ... }
}
Since your title says you wish to use a session:
class Blocka_Model extends Block_Model {
protected $session_unique_id;
public function __construct() {
$this->session_unique_id = uniqid();
}
/*
* Save $val in our current session
*/
public function input($val) {
$_SESSION[get_class($this).$this->session_unique_id] = $val;
}
/*
* Check for a value in our session
* - if it is set, return it
* - else return null
*/
public function output() {
return isset($_SESSION[get_class($this).$this->session_unique_id]) ?
$_SESSION[get_class($this).$this->session_unique_id] : null;
}
}