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();
Related
The idea here is to make a class that constructs with a function and an array of parameters and calls that function in a new thread.
This is my class so far:
class FunctionThread extends Thread {
public function __construct($fFunction, $aParameters){
$this->fFunction = $fFunction;
$this->aParameters = $aParameters;
}
public function run(){
$this->fFunction($this->aParmeters[0], $this->aParmeters[1], ...);
}
}
Obviously the run function is incorrect, which brings me to my question:
Assuming the array is guaranteed to have the proper number of elements to match the function that is being called, How can I call a function in PHP with an unknown number of arguments that are stored in an array?
Edit:
Also I have no access to the contents of the given function so it cannot be edited.
Edit 2: I'm looking for something similar to scheme's curry function.
As of PHP 5.6, this is now possible. Arrays can be expanded into the argument list using the ... operator like so:
<?
class FunctionThread extends Thread {
public function __construct($fFunction, $aParameters){
$this->fFunction = $fFunction;
$this->aParameters = $aParameters;
}
public function run(){
$this->fFunction(... $this->aParmeters);
}
}
?>
See here for more information
I think that function should accept in its case the arg array
class FunctionThread extends Thread {
public function __construct($fFunction, $aParameters){
$this->fFunction = $fFunction;
$this->aParameters = $aParameters;
}
public function run(){
$this->fFunction($this->aParmeters);
}
public function fFunction($arr){
$var0 = $arr[0];
$var1 = $arr[1];
...
do
..
}
}
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();
?>
I'm working on a project which requires a function to be copied & executed on the fly and variables in it needs to be replaced on the fly too.
A simple example will be like this:
function myfunction()
{
$abc = $_SESSION['abc'];
return $abc;
}
I want to be able to call myfunction1() which does NOT physically exist in the code but does exactly the samething as the one above except it now take values from my custom variable so it'll look like this:
function myfunction1()
{
$abc = $myCustomVariable;
return $abc;
}
Any one help pls?
The more you describe how convoluted your function is, the more it sounds like a perfect candidate for an object with injected dependencies.
For instance, you could have (just going to describe the basic interfaces here):
class myClass
{
public function __construct($provider DataProvider)
{
$this->provider = $provider;
}
// Please name this something better
public function doStufferer()
{
if ($this->provider->hasParam('foo'))
{
return $this->provider->getParam('foo');
}
}
}
class SessionProvider implements DataProvider
{
// Session specific stuff
}
class OtherProvider implements DataProvider
{
// Other provider stuff
}
interface DataProvider
{
public function getParam($key);
public function hasParam($key);
public function setParam($key, $value);
}
You can then use it like this:
$dataProcessor = new myClass(new SessionProvider);
// OR $dataProcessor = new myClass(new OtherProvider);
$dataProcessor->doStufferer();
Please take a look at PHP Classes and Objects and the other related topics.
This is what parameters are for, I think your looking todo something like this:
$myCustomVariable = 'Some value';
function myfunction($var=$_SESSION['abc'])
{
$abc = $var;
return $abc;
}
myfunction(); //returns $_SESSION['abc']
myfunction($myCustomVariable); //returns "Some Value"
The direct answer is eval which I do not recommend.
You could have your function accept a parameter, like this.
function myfunction1($some_var)
{
$abc = $some_var;
return $abc;
}
// call it like...
myfunction1($myCustomVariable);
If you need to access a variable, but the name is generated by dynamic code, you can use $GLOBALS.
function myfunction1($name_of_var)
{
$abc = $GLOBALS[$name_of_var];
return $abc;
}
// call it like...
$myCustomVariable = 'a value'
myfunction1('myCustom' + 'Variable');
I know you can assign a function's return value to a variable and use it, like this:
function standardModel()
{
return "Higgs Boson";
}
$nextBigThing = standardModel();
echo $nextBigThing;
So someone please tell me why the following doesn't work? Or is it just not implemented yet? Am I missing something?
class standardModel
{
private function nextBigThing()
{
return "Higgs Boson";
}
public $nextBigThing = $this->nextBigThing();
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing; // get var, not the function directly
I know I could do this:
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing(); // Call to the function itself
But in my project's case, all of the information stored in the class are predefined public vars, except one of them, which needs to compute the value at runtime.
I want it consistent so I nor any other developer using this project has to remember that one value has to be function call rather then a var call.
But don't worry about my project, I'm mainly just wondering why the inconsistency within PHP's interpreter?
Obviously, the examples are made up to simplify things. Please don't question "why" I need to put said function in the class. I don't need a lesson on proper OOP and this is just a proof of concept. Thanks!
public $nextBigThing = $this->nextBigThing();
You can only initialize class members with constant values. I.e. you can't use functions or any sort of expression at this point. Furthermore, the class isn't even fully loaded at this point, so even if it was allowed you probably couldn't call its own functions on itself while it's still being constructed.
Do this:
class standardModel {
public $nextBigThing = null;
public function __construct() {
$this->nextBigThing = $this->nextBigThing();
}
private function nextBigThing() {
return "Higgs Boson";
}
}
You can't assign default values to properties like that unless that value is of a constant data type (such as string, int...etc). Anything that essentially processes code (such as a function, even $_SESSION values) can't be assigned as a default value to a property. What you can do though is assign the property whatever value you want inside of a constructor.
class test {
private $test_priv_prop;
public function __construct(){
$this->test_priv_prop = $this->test_method();
}
public function test_method(){
return "some value";
}
}
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel(); // corection
echo $standardModel->nextBigThing();