Call static function from variable - php

I have the following setup:
class test {
public static function something() {
$somethingElseFunction = "somethingElse";
// How can I call the method with the name saved in variable?
}
public static function somethingElse($a) {
echo 'bla';
}
}
How can I call the function using the variable? (the function name is in variable).
Also I need to do a function_exists() for it.
Tried this:
if (function_exists(self::$somethingElseFunction ())) {
if (!call_user_func(self::$somethingElseFunction , $a)) {
}
}
Didn't work.

In PHP>=5.4 you can use just self:: de-reference:
self::$somethingElseFunction();
-but in earlier versions that will cause error (because it wasn't allowed to use dynamic static methods de-reference). So then you can always use such things as call_user_func_array() :
class test {
public static function something() {
$somethingElseFunction = "somethingElse";
call_user_func_array(array(__CLASS__, $somethingElseFunction), array("bla"));
}
public static function somethingElse($a) {
var_dump($a);
}
}
test::something();
-this will work for PHP>=5.0
About function_exists() call - it expects string as parameter, thus I recommend to use method_exists() - because that function is intended to do the stuff:
public static function something() {
$somethingElseFunction = "somethingElse";
if(method_exists(__CLASS__, $somethingElseFunction))
{
call_user_func_array(array(__CLASS__, $somethingElseFunction), array("bla"));
}
}

You should be able to use the following:
test::$somethingElseFunction();

Use this function:
$classname = 'somethingElse';
call_user_func('test::' . $classname, $params);

Related

Return array variable in PHP

I have a function and I'd like to return a variable to another function.
Can I return the array variable so I can use the variable at other function?
public function update_mdr_pameran() {
//global $araydatamdr;
$this->config->set_item('compress_output', FALSE);
$araydatamdr['mdr_debit'] = trim($this->input->post('mdr_debit'));
$araydatamdr['mdr_debit_npg'] = trim($this->input->post('mdr_debit_npg'));
$araydatamdr['mdr_debit_pl'] = trim($this->input->post('mdr_debit_pl'));
return $araydatamdr;
}
When I try to use $araydatamdr in another function, it became 0.
Am I missing something?
You can achieve this by calling function and setting its return value to another variable.
Method 1 :
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function update_mdr_pameran() {
//global $araydatamdr;
$this->config->set_item('compress_output', FALSE);
$araydatamdr['mdr_debit'] = trim($this->input->post('mdr_debit'));
$araydatamdr['mdr_debit_npg'] = trim($this->input->post('mdr_debit_npg'));
$araydatamdr['mdr_debit_pl'] = trim($this->input->post('mdr_debit_pl'));
return $araydatamdr;
}
public function test_func() {
$araydatamdr = $this->update_mdr_pameran();
var_dump($araydatamdr);
}
}
Or you can also set $araydatamdr to $this reference.
Method 2 :
class Test extends CI_Controller {
public $araydatamdr;
public function __construct() {
parent::__construct();
$this->araydatamdr = [];
}
public function update_mdr_pameran() {
$this->config->set_item('compress_output', FALSE);
$this->araydatamdr['mdr_debit'] = trim($this->input->post('mdr_debit'));
$this->araydatamdr['mdr_debit_npg'] = trim($this->input->post('mdr_debit_npg'));
$this->araydatamdr['mdr_debit_pl'] = trim($this->input->post('mdr_debit_pl'));
}
public function test_func() {
$this->update_mdr_pameran();
var_dump($this->araydatamdr);
}
}
Cross out the echo $araydatamdr; Arrays can be printed using var_dump or print_r. Also you can return an array in php but personally i prefer to json_encode it first so i return a json as the output of my function something like:
return json_encode($araydatamdr);
Then it's a simple function call.
I don't know your project structure but i am giving general guidance. Apart from that i don't see anything else that could block your function.
I edit my post because i saw the issue is to call the function. There are 2 ways depending where you call it. If the function is in the same class as the other function you want to call it you simple go for :
$result=$this->update_mdr_pameran();
I see that your function has no arguments so you don't need to set any. If it's in another file:
1) include your php file at top like :
require 'myphpclass.php';
*tip make sure your path is right.
2) Create a new class object and then call the function like :
$class= new myClass();
$result=$class->update_mdr_pameran();

Referencing class function variables in php

I've been looking over the PHP variable scope reference page and I can't seem to find a clear answer. I'm working with this basic model where I want to call a class function and have all of its variables accessible outside the class. I want to avoid using the global declaration as well and do this in the most efficient way possible.
class my_class() {
function my_class_function() {
$my_class_function_variable = 'juice';
return $my_class_function_variable;
}
}
$class_instance = new my_class();
function display_juice() {
$class_instance::my_class_function();
$my_class_function_variable;
}
Is there a quick answer in what I'm missing? I'm not getting any output or errors.
EDIT
I'm getting a syntax error when I declare the following within the class but not within the function.
public $current_user = wp_get_current_user();
Parse error: syntax error, unexpected '(', expecting ',' or ';'
You can access all setted variables in class if they are public.
And you can access any of its function if its again public...
Here is example . I have default value 'mydefault'.
I use it, then I change it and again I use it..
class my_class {
public $variable = "mydefault";
public function change_variable($value) {
$this->variable = $value;
}
}
function display_juice() {
$class = new my_class;
echo $class->variable; // echo default value - 'mydefault'
$class->change_variable('newvalue');
echo $class->variable; // echo default value - 'newvalue'
}
display_juice();
Edit..
class my_class {
public $variable;
public function __construct() {
$this->variable = wp_get_current_user();
}
}
You need to make my_class_function() static, the you can call it with my_class::my_class_function()
http://php.net/manual/en/language.oop5.static.php
Also as suggested bellow, you need to return 'juice'.
return 'juice';
You currently don't return anything, you would have to do something like this:
class my_class() {
function my_class_function() {
$my_class_function_variable = 'juice';
return $my_class_function_variable;
}
}
function display_juice() {
$class_instance = new my_class(); //Needs to be inside the function
$my_class_function_variable = $class_instance->my_class_function();
echo $my_class_function_variable;
}
display_juice();
If you want to use a static function or variable you could do this, which eliminates the need for having to create an instance of my_class:
class my_class() {
static function my_class_function() {
return 'juice';
}
}
function display_juice() {
$my_class_function_variable = my_class::my_class_function();
echo $my_class_function_variable;
}
display_juice();
I would make the variable you're trying to access a public member
class my_class {
public $my_class_function_variable = 'juice';
public function my_class_function() {
}
}
$class_instance = new my_class();
function display_juice() {
echo my_class->$my_class_function_variable;
}
display_juice();

php: how to make a method inside a class run?

I started learning oop php and I don't understand how to make a method inside a class execute.
This is the code:
class GrabData {
public $tables=array();
public $columns=array();
public $argList;
function __construct(){
$this->argList=func_get_args();
$pattern;
var_dump($this->argList);
if(!empty($this->argList)){
foreach($this->argList as $value){
if(preg_match("/.+_data/",$value,$matches)){
if(!in_array($matches[0],$this->tables)){
array_push($this->tables,$matches[0]);
var_dump($this->tables);
}
$pattern="/". $matches[0] . "_" . "/";
array_push($this->columns,preg_replace($pattern,"",$value));
var_dump($this->columns);
}
}
}
}
public function gen_query(){
var_dump($this->argList);
echo "haha";
}
gen_query();
}
new GrabData("apt_data_aptname");
Now, the __construct function runs when I make a new GrabData object, but the gen_query function doesnt execute. How do I make it execute it ?
If you always want to have the gen_query function run when the class is initiated, you could link to it in the bottom of your constructor, like so:
function __construct() {
// Do your stuff here and then...
$this->gen_query();
}
First, you assign the object returned by the new operator to a variable - then use that variable to execute methods on your object:
class GrabData {
public $tables=array();
public $columns=array();
public $argList;
function __construct() {
$this->argList=func_get_args();
$pattern;
var_dump($this->argList);
if(!empty($this->argList)){
foreach($this->argList as $value){
if(preg_match("/.+_data/",$value,$matches)){
if(!in_array($matches[0],$this->tables)){
array_push($this->tables,$matches[0]);
var_dump($this->tables);
}
$pattern="/". $matches[0] . "_" . "/";
array_push($this->columns,preg_replace($pattern,"",$value));
var_dump($this->columns);
}
}
}
}
public function gen_query() {
var_dump($this->argList);
echo "haha";
}
}
$super_object = new GrabData("apt_data_aptname");
$super_object->gen_query();
A different way to run a class function without initiating the class is to use the double colon scope resolution operator, strangely called "Paamayim Nekudotayim".
GrabData::gen_query();
You can read up on it here.

Passing a parameter from a parent to a child function

I'm trying to pass a parameter from a parent function to a child function while keeping the child function parameterless. I tried the following but it doesn't seem to work.
public static function parent($param)
{
function child()
{
global $param;
print($param) // prints nothing
}
}
You can use lambda functions from PHP 5.3 and on:
public static function parent($param) {
$child = function($param) {
print($param);
}
$child($param);
}
If you need to do it with earlier versions of PHP try create_function.
I think that the global you call in child() does not refer to that scope. Try running it with really global variable.
The right way to do this there would be to create an anonymous function inside your parent function, and then use the ''use'' keyword.
public static function parent($params) {
function() use ($params) {
print($params);
}
}
https://www.php.net/manual/en/functions.anonymous.php

Calling a changing function name on an object with PHP : how?

How would I do something like this :
class Test
{
public function test($methodName) {
$this->$methodName;
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a()");
$testObj->test("b()");
Maybe I should just pass a parameter "TYPE" and use a "IF statement" but I'm just curious! :)
And what if the "dynamic function name" has one or more parameters?
UPDATE : Thanks everyone! :)
UPDATE #2 - Answer :
class Test
{
public function testOut($methodName) {
$this->$methodName();
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->testOut("a");
$testObj->testOut("b");
The problem with the class is that there was a method named "Test" (the same as the class name)... I changed it and it worked.
class Test
{
public function test($methodName) {
$this->$methodName();
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a");
$testObj->test("b");
Check out call_user_func() - it should do what you want.
Documentation here
call_user_func allows you to do things like this.
For example,
funcname = 'a';
call_user_func(array($testObj, $funcname));
The other alternative is to use variable methods
For example,
$funcname = 'a';
$testObj->$funcname();
If you have a "dynamic function name" with more than one parameter, you can use call_user_func_array, like this:
//in class context..
//$parameters can be an array like array(1,2)
call_user_func_array(array($this, $methodName), $parameters);
The reason you would want to use call_user_func_array instead of call_user_func is that you can pass the parameters the function takes as an array, instead of just as additional parameters, thus allowing you to easily have a variable number of arguments.
Following your particular example and use case, the only way to achieve this exactly:
$testObj = new Test();
$testObj->test("a()");
$testObj->test("b()");
would be to use eval():
class Test
{
public function test($methodName) {
eval($methodName);
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a()");
$testObj->test("b()");
Others pointed out a solution using call_user_func() and rightly so. Also evidently, is faster than using eval() for function calls. Read this:
http://nz.php.net/manual/en/function.call-user-func.php#64415

Categories