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
Related
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();
With PHP's ob_start($callback), you can pass a static method as a callback like this:
class TemplateRenderer {
function myCallback($bufferContents) {
return 'Foobar instead of the buffer';
}
}
ob_start(array('TemplateRenderer', 'myCallback'));
Or you can refer to an object like this:
$myTemplateRenderer = new TemplateRenderer();
ob_start(array($myTemplateRenderer, 'myCallback'));
Both of these work, but I'd like to know if I can start the output buffer from within a class method, and refer to the callback using $this
class TemplateRenderer {
function myCallback($bufferContents) {
return 'Foobar instead of the buffer';
}
function init() {
// --- this doesn't work ----
ob_start(array($this, 'myCallback'));
// --- this doesn't work either ----
ob_start(array('this', 'myCallback'));
}
}
TemplateRenderer::init();
If it's even possible, what's the syntax for referring to a "callable" from within its own class?
I would follow Barmar's suggestion, but if you for whatever reason don't want to make instantiation, you can try this solution:
class TemplateRenderer {
static function myCallback($bufferContents) {
return 'Foobar instead of the buffer';
}
function init() {
ob_start(array('self', 'myCallback'));
}
}
TemplateRenderer::init();
You need to call init() using an object so that $this will be set.
$myTemplateRenderer = new TemplateRenderer();
$myTemplateRenderer->init();
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);
I try to create some sort of setup class, like global values for the page.
The PHP-code
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
Question
My class forget the value I set. Why is that?
Do I have to use global variables?
Is this the correct approach for the problem?
The variable is set on an object, not on a class.
For each class, you can instantiate multiple objects. Each of those have their own variable scope.
Edit:
I forgot to include the easiest, and least verbose solution to your problem. AFAIK, you're looking for a way to check what page you're on. Constants will do just that:
defined('MY_CURRENT_PAGE') || define('MY_CURRENT_PAGE','My Value');
//use anywhere like so:
echo 'Currently on page: '.MY_CURRENT_PAGE;
My class forget the value I set. Why is that?
Quite simple: your page member function isn't static, yet you call it as though it is: get::page(). Even if you were to fix this, you're creating a new instance in the page method, but you're not preserving a reference too it anywhere, so each page call will create a new globals instance, that has nothing set.
Do I have to use global variables?
No, unless you're Really desperate, never use globals
Is this the correct approach for the problem?
No, if it doesn't work, it's not correct (IMHO).
Well, what is, you might ask. There are several ways to go about this:
class globals
{
public static $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
private $_globalsInstance = null;
public function __construct(globals $instance = null)
{
$this->_globalsInstance = $instance;
}
private function _getGlobals()
{
if (!$this->_globalsInstance instanceof globals)
{
$this->_globalsInstance = new globals();
}
return $this->_globalsInstance;
}
public function page()
{
return $this->_getGlobals()::$page;
}
}
Personally, however, I wouldn't work like this, I'd just pass my instances to wherever I need them (as arguments to functions/methods or just instantiate them in a scope that will be accessible:
class globals
{
public $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
$page = new globals();
$page->set_page('foobar');
someFunction($page);
$someObject->renderPage($page);
require_once('specificScript.php');
//inside required script:
echo $page->page;
Do I have to use global variables?
Not, if your can use PHP 5.3
Is this the correct approach for the problem?
Better to use a generic class for this, or use static properties of objects
<?php
class globals
{
public static $page;
public function __construct()
{
}
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
public static function page()
{
return globals::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
P.S.
But this is not a nice approach
$globals there
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
and there
$globals = new globals();
$globals->set_page('My value');
are different inctances of globals class.
One of the solutions is to make $page var static
public static $page;
I hope this helps
UPD:
Also you might apply Singleton to globals class and request for its insnance instead of creating new one directly:
globals::getInstance()->setPage('Page');
and
return globals::getInstance()->getPage();
In this case $page doesn't have to be static.
I'm not sure the other answers are very clear. You have created 2 classes. As such they have different scopes. As writen you can't access the original variable $page from the get class because it's outside the scope. Your page function in fact creates a new version of the object $globals without $page set. Normally you would place both your set and get functions in the initial object/class. Though it would be possible to use two class by calling the first class from the second and setting the page. Why you would want to do that I'm not sure.
if I were writing the class it would look like this.
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
public function get_page()
{
return $this->page;
}
}
Actually I would probably set page to private not public. As public I guess you don't need a get function.
for using methods of the class without object you must use static definition. but anyway you put value for one class object and try to get it from another...
Perhaps this will help you continue on your coarse:
class globals
{
public static $page;
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get extends globals
{
public function page()
{
$globals = new globals();
return parent::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page();
?>
here is an example class:
public class example
{
private $foof;
public function __construct()
{
$this->foof = $this->foo;
}
public function foo($val=0)
{
// do something...
}
}
So basically, in the constructer of the sample code, is it possible to assign a class method to a variable?
Ultimately what i want is to have an associative array with all the class methods aliased in it...that possible in php?
In PHP5.3+ (which you should be using anyway!) you can simply create an anonymous function which calls your method:
$this->foof = function() {
$this->foo(1);
};
However, you cannot call it using $this->foof() - you have to assign it to a variable first: $foof = $this->foof; $foof();
In older PHP versions you cannot easily do this - create_function() does not create a closure so $this is not available there.
You don't need to use anonymous functions. Just use the Callable pseudo type.
$this->foof = array($this, 'foo');
...
call_user_func($this->foof);