This seems simple but I can not get a result of a function and take it to another function as I can do
function Operation() {
$result=5; return $result;
}
Going out on a limb here...
invoke (call) function Operation(), you get 5 returned, store that in $result.
invoke function Operation2($result) with argument $result.
Output: 6
<?php
function Operation()
{
$result = 5;
return $result;
}
function Operation2($result)
{
$all = $result +1;
echo $all;
}
$result = Operation();
Operation2($result); // output: 6
live demo
You might be a bit confused about functions and variable scope; I'd recommend you take a look at this
Related
I am building a scheduler that will take a callback function and will execute that function a given amount of times, and in between a given amount of delay. Below is that the interface for what the functionality looks like.
Side note I am using the Laravel Framework;
public function testBasicTest()
{
$count = 0;
$schedule = new NodeScheduler();
$schedule->retries(2)->delay(100000)->do(function() use ($count) {
$count++;
});
$this->assertEquals($count === 1);
}
This is my test for this piece of functionality and as you can see i want count to equal 2 by the end of it.
My class looks like this;
class NodeScheduler
{
protected $retries = 1;
protected $milliseconds = 10000;
public function __construct()
{
return $this;
}
public function retries($numberOfRetries)
{
$this->retries = $numberOfRetries;
return $this;
}
public function delay($milliSeconds)
{
$this->milliSeconds = $milliSeconds;
return $this;
}
public function do($callback)
{
for($i = 0; $i < $this->retries; $i++){
$callback(); // <<<<<< How Do I Inject The $count Variable Here?
usleep($this->milliseconds);
}
return;
}
}
My test fails with:
Failed asserting that 2 matches expected 0.
Strangely I don't get $count is undefined.
I think i am close, any help greatly appreciated
When you use() a variable from the outer scope inside a function, this creates a copy of the variable into the function's inner scope (an exception is if you're use()ing an object).
If you want to import a variable from the outer scope and modify it, you'll need to pass it in by reference:
$schedule->retries(2)->delay(100000)->do(function() use (&$count) {
$count++;
});
Edit: Also, what #Arno and #Oniyo pointed out: either use assertEquals(1, $count) or use assertTrue($count === 1)
I think you are doing two things wrong
Firstly: As #Arno pointed out,
$this->assertEquals($expected, $actual);
Secondly: From what I see in your code, the loop will run $this->retries's iterations. So, $this->assertEquals($expected, $actual) should be
$this->assertEquals(2, count);
Good luck man!
i have got the following recursive function:
private function myRecursiveFunction()
{
$results = [];
//stuff related to $results
...
if(!$done){
.....
$this->myRecursiveFunction();
}
return $results;
}
when i do var_dump($results) inside function i got the all array results
but when i call the function from another one i will got only the first element in $results array.
public function myFunction()
{
$results = $this->myRecursiveFunction();
}
I am not 100% sure what you wish to accomplish here, but recursive functions usually send their "workload" all the way to the innermost function, then the results are "added" on each other at the way back. If this is indeed what you want, you may need to change your code to something like this:
private function myRecursiveFunction()
{
$results = [];
//stuff related to $results
...
if(!$done){
.....
// Add the computed results of the recursive call to our data stack
$results[] = $this->myRecursiveFunction();
}
// Return the entire result array
return $results;
}
I have a function that returns a multidimensional array, but I also need to return a single value. I am currently using the single value via the global keyword, so I can modify it inside the function.
But I'm wondering if there is another/better way to return 2 values from a function?
Current (pseudo) code:
global $iNumber;
$arrResult;
{do some calculations and queries}
$iNumber = 73;
return $arrResult;
The function that called this function can use the array of arrays, and also the global variable which has been updated to 73.
But is there another/better way to combine or pass these two different values?
You can do it in two ways: to return an array or an object.
Array solution:
function calculate(...) {
//do some stuff
return ['result' => $arrResult, 'iNumber' => $iNumber];
}
Object solution:
function calculate(...) {
//do some stuff
$object = new stdClass();
$object->result = $arrResult;
$object->iNumber = $iNumber;
return $object;
}
stdClass is just an example and you can create your own class for this purpose.
You can make a class and use a class variable.
Something like this:
class Test
{
public $iNumber;
function __construct()
{
# code...
}
public function yourCal()
{
// you calculations
$this->setNumber(73);
return $arrayOfArrays;
}
public function getNumber()
{
return $this->iNumber;
}
public function setNumber($var)
{
$this->iNumber = $var;
}
}
// Use the class in another php file
include 'Test.php';
$test = new Test();
// do calculations
$arrayOfArrays = $test->yourCal();
// get the number
$iNumber = $test->getNumber();
echo $iNumber; // returns 73
print_r($arrayOfArrays); // print your array
I am trying to understand object oriented PHP programming and wrote a small class to learn. I am having trouble understanding why its not working the way I intend. I have two variables inside the class method hello() $result and $test. I am trying to access the data that is stored in those two variables and print it to the screen. I know I can just call an echo inside the method but I am trying to get it to echo outside of it.
What I get printed to the screen is 88 it does not print out the second variable $test. I am trying to understand why thats happening. My lack of understanding probably shows in the code.
<?php
class simpleClass{
public function hello($result,$test) {
$result = 4+4;
$test = 10+5;
return $result;
return $test;
}
}
$a = new simpleClass;
echo $a->hello();
echo $a->hello($result, $test);
?>
you can return a list or array
public function hello($result,$test) {
$result = 4+4;
$test = 10+5;
return array($result, $test);
}
Use parameter referencing :
class simpleClass{
public function hello(&$result, &$test) {
$result = 4+4;
$test = 10+5;
}
}
$a = new simpleClass;
$result=''; $test='';
$a->hello($result, $test);
echo $result;
echo '<br>';
echo $test;
8
15
To clarify, when you add & to a function param, the value of that param - if you change or manipulate it inside the function - is handled back to your original variable passed. So you dont even have to return a result, and lets say pack it into an array or stdObject and unpack it afterwards. But you can still return something from the function, eg
$ok = $a->hello($result, $test);
as a flag to indicate if the calculation went right, for instance.
You cannot have multiple return statements in the same function because of the way return works. When a return statement is encountered the function stops executing there and then, passing back to the caller. The rest of the function never runs.
The complicated answer is to use a model.
class simpleResultTestModel {
public $result;
public $test;
public function __construct($result,$test) {
$this->result = $result;
$this->test = $test;
}
}
class simpleClass {
public function hello($result=4, $test=10) {
$result = $result+4;
$test = $test+5;
return new simpleResultTestModel($result, $test);
}
}
This way, you know simpleClass->hello() will always return an instance of simpleResultTestModel.
Also, I updated your hello method definition. You have two parameters, but don't actually apply them; I took the liberty of setting default values and then used them in the computation.
Usage:
$a = new simpleClass();
$first = $a->hello();
echo $first->result;
echo $first->test;
$second = $a->hello($first->result,$first->test);
echo $second->result;
echo $second->test;
I would try to stay away from passing by reference (especially within a class definition) unless you have a legitimate reason for doing so. It is bad practice when creating instances of classes (i.e. "sticky values" if you will).
I've been wondering whether it is possible or not to pass a function as a parameter in PHP. I want something similar to when you're programming the following code in JavaScript:
object.exampleMethod(function(){
// some stuff to execute
});
What I want is to execute that function somewhere in exampleMethod. Is that possible in PHP?
It's possible if you are using PHP 5.3.0 or higher.
See Anonymous Functions in the manual.
In your case, you would define exampleMethod like this:
function exampleMethod($anonFunc) {
//execute anonymous function
$anonFunc();
}
Just to add to the others, you can pass a function name:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
This will work in PHP4.
Valid: (PHP 4 >= 4.0.1, PHP 5, PHP 7)
You can also use create_function to create a function as a variable and pass it around. Though, I like the feeling of anonymous functions better. Go zombat.
Update 09 - Jan - 2022
Warning
This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.
Just code it like this:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
it would be great if you could invent something like this (inspired by Laravel Illuminate):
Object::method("param_1", function($param){
$param->something();
});
PHP VERSION >= 5.3.0
Example 1: basic
function test($test_param, $my_function) {
return $my_function($test_param);
}
test("param", function($param) {
echo $param;
}); //will echo "param"
Example 2: std object
$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
return $my_function($test_param);
};
$test = $obj->test;
$test("param", function($param) {
echo $param;
});
Example 3: non static class call
class obj{
public function test($test_param, $my_function) {
return $my_function($test_param);
}
}
$obj = new obj();
$obj->test("param", function($param) {
echo $param;
});
Example 4: static class call
class obj {
public static function test($test_param, $my_function) {
return $my_function($test_param);
}
}
obj::test("param", function($param) {
echo $param;
});
According to #zombat's answer, it's better to validate the Anonymous Functions first:
function exampleMethod($anonFunc) {
//execute anonymous function
if (is_callable($anonFunc)) {
$anonFunc();
}
}
Or validate argument type since PHP 5.4.0:
function exampleMethod(callable $anonFunc) {}
Tested for PHP 5.3
As i see here, Anonymous Function could help you:
http://php.net/manual/en/functions.anonymous.php
What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function.
As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.
The function to do check:
if( is_callable( $string_function_name ) ){
/*perform the call*/
}
Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php
call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );
as it follows (in a similar, parameterless, way):
function funToBeCalled(){
print("----------------------i'm here");
}
function wrapCaller($fun){
if( is_callable($fun)){
print("called");
call_user_func($fun);
}else{
print($fun." not called");
}
}
wrapCaller("funToBeCalled");
wrapCaller("cannot call me");
Here's a class explaining how to do something similar :
<?php
class HolderValuesOrFunctionsAsString{
private $functions = array();
private $vars = array();
function __set($name,$data){
if(is_callable($data))
$this->functions[$name] = $data;
else
$this->vars[$name] = $data;
}
function __get($name){
$t = $this->vars[$name];
if(isset($t))
return $t;
else{
$t = $this->$functions[$name];
if( isset($t))
return $t;
}
}
function __call($method,$args=null){
$fun = $this->functions[$method];
if(isset($fun)){
call_user_func_array($fun,$args);
} else {
// error out
print("ERROR: Funciton not found: ". $method);
}
}
}
?>
and an example of usage
<?php
/*create a sample function*/
function sayHello($some = "all"){
?>
<br>hello to <?=$some?><br>
<?php
}
$obj = new HolderValuesOrFunctionsAsString;
/*do the assignement*/
$obj->justPrintSomething = 'sayHello'; /*note that the given
"sayHello" it's a string ! */
/*now call it*/
$obj->justPrintSomething(); /*will print: "hello to all" and
a break-line, for html purpose*/
/*if the string assigned is not denoting a defined method
, it's treat as a simple value*/
$obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';
echo $obj->justPrintSomething; /*what do you expect to print?
just that string*/
/*N.B.: "justPrintSomething" is treated as a variable now!
as the __set 's override specify"*/
/*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
$obj->justPrintSomething("Jack Sparrow");
/*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/
$obj->justPrintSomething( $obj->justPrintSomething );
/*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/
/*in fact, "justPrintSomething" it's a name used to identify both
a value (into the dictionary of values) or a function-name
(into the dictionary of functions)*/
?>
Simple example using a class :
class test {
public function works($other_parameter, $function_as_parameter)
{
return $function_as_parameter($other_parameter) ;
}
}
$obj = new test() ;
echo $obj->works('working well',function($other_parameter){
return $other_parameter;
});
Here is a simple procedural example of how you could implement validation of multiple data items using separate functions for each data item validation, passed as an array of functions argument to a master validations function, with the data to be validated (the arguments to the functions) passes as the other array argument to the master validation function. Useful for writing generic code to validate form data.
<?php
function valX($value) {
echo "<p>Validating $value == 5</p>";
if ($value == 5) {
return true;
} else {
return false;
}
}
function valY($value) {
echo "<p>Validating $value == 6</p>";
if ($value == 6) {
return true;
} else {
return false;
}
}
function validate($values, $functions) {
for ($i = 0; $i < count($values); $i++) {
if ($functions[$i]($values[$i])) {
echo "<p>$values[$i] passes validation</p>";
} else {
echo "<p>$values[$i] fails validation</p>";
}
}
}
$values = [5, 9];
$functions = ['valX', 'valY'];
validate($values, $functions);
?>