Calling the same function within another via parameter - php

I have an existential doubt, I can not do that within a parameter that becomes a callback function enter and manipulate the same function, I have no idea what this would be like, but in this example it shows it.
<?php
class where{
public function show_sql( $params ){
if( is_numeric($params) ){
echo "Number $params <br />";
}elseif( is_callable($params) ) { // here validate if function
// get_defined_vars() <--- I get the variables but I can not manipulate same function
}
return $this;
}
}
$DB = new where;
$DB->show_sql(12)
->show_sql(13)
->show_sql(function ($object){
$object->show_sql(14);
});
?>
The result would be
Number 12
Number 13
But the number 14 is not shown and I call it in the same function.
I want to have the same result as Laravel does in this example: https://laravel.com/docs/master/queries#where-clauses go to Parameter Grouping
Someone could help me ?

You need to execute your callback.
You can use call_user_func_array() and pass the object as parameter:
}elseif( is_callable($params) ) {
call_user_func_array($params, [$this]);
}

Related

Unexpected Result from User Defined Function - PHP

I'm trying to write a simple function which takes two arguments, adds them together and returns the result of the calculation.
Before performing the calculation the function checks whether either of the two arguments are undefined and if so, sets the argument to 0.
Here's my function:
Function - PHP
function returnZeroAdd ($arg, $arg2)
{
if(!isset($arg))
{
$arg = 0;
}
if(!isset($arg2))
{
$arg2 = 0;
}
echo $arg + $arg2;
}
I've tried to execute it like so :
returnZeroAdd($bawtryReturnCount, $bawtryFReturnCount);
But this throws up an undefined variable $bawtryFReturnCount error.
I do not know why the function isn't setting $bawtryFReturnCount) to 0 before performing the calculation thereby negating the 'undefined variable' error.
Can anybody provide a solution?
You cannot do this the way you want. As soon as you use an undefined variable, you will get this error. So the error doesn't occur inside your function, but already occurs in the call to your function.
1. Optional parameters
You might make a parameter optional, like so:
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
return $arg + $arg2;
}
This way, the parameter is optional, and you can call the function like this:
echo returnZeroAdd(); // 0
echo returnZeroAdd(1); // 1
echo returnZeroAdd(1, 1); // 2
2. By reference
But I'm not sure if that is what you want. This call will still fail:
echo returnZeroAdd($undefinedVariable);
That can be solved by passing the variables by reference. You can then check if the values are set and if so, use them in the addition.
<?php
function returnZeroAdd (&$arg, &$arg2)
{
$result = 0;
if(isset($arg))
{
$result += $arg;
}
if(isset($arg2))
{
$result += $arg2;
}
return $result;
}
echo returnZeroAdd($x, $y);
Note that you will actually change the original value of a by reference parameter, if you change it in the function. That's why I changed the code in such a way that the parameters themselves are not modified. Look at this simplified example to see what I mean:
<?php
function example(&$arg)
{
if(!isset($arg))
{
$arg = 0;
}
return $arg;
}
echo example($x); // 0
echo $x // also 0
Of course that might be your intention. If so, you can safely set $arg and $arg2 to 0 inside the function.
The error is not thrown by the function itself, as the function is not aware of the global scope. The error is thrown before even the function is executed, while the PHP interperter is trying to pass $bawtryFReturnCount to the function, one does not find it, and throws error, however, it's not a fatal one and the execution is not stopped. THerefore, the function is executed with a non-set variable with default value of null, where I guess, isset will not work, as the arguments are mandatory, but not optional. A better check here will be empty($arg), however the error will still be present.
Because the functions are not and SHOULD NOT be aware of the global state of your application, you should do these checks from outside the functions and then call it.
if (!isset($bawtryReturnCount)) {
$bawtryReturnCount = 0
}
returnZeroAdd($bawtryReturnCount);
Or assign default values to the arguments in the function, making them optional instead of mandatory.
Your function could be rewritten as:
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
echo $arg + $arg2;
}
You missunderstand how variables work. Since $bawtryFReturnCount isn't defined when you call the function; you get a warning. Your isset-checks performs the checks too late. Example:
$bawtryReturnCount = 4;
$bawtryFReturnCount = 0;
returnZeroAdd($bawtryReturnCount, $bawtryFReturnCount);
Will not result in an error.
If you really want to make the check inside the function you could pass the arguments by reference:
function returnZeroAdd (&$arg, &$arg2)
{
if(!isset($arg))
{
$arg = 0;
}
if(!isset($arg2))
{
$arg2 = 0;
}
echo $arg + $arg2;
}
However this will potentially modify your arguments outside the function, if it is not what you intend to do then you need this:
function returnZeroAdd (&$arg, &$arg2)
{
if(!isset($arg))
{
$localArg = 0;
}
else
{
$localArg = $arg;
}
if(!isset($arg2))
{
$localArg2 = 0;
}
else
{
$localArg2 = $arg2;
}
echo $localArg + $localArg2;
}
You can now pass undefined variables, it won't throw any error.
Alternatively you might want to give a default value to your arguments (in your case 0 seems appropriate):
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
echo $arg + $arg2;
}
You have to define the variable before pass it to an function. for example
$bawtryReturnCount=10;
$bawtryFReturnCount=5;
define the two variable with some value and pass it to that function.
function returnZeroAdd ($arg=0, $arg2=0)
{
echo $arg + $arg2;
}
if you define a function like this means the function takes default value as 0 if the argument is not passed.
for example you can call the functio like this
returnZeroadd();// print 0
returnZeroadd(4);// print 4
returnZeroadd(4,5);// print 9
or you can define two variables and pass it as an argument and call like this.
$bawtryReturnCount=10;
$bawtryFReturnCount=5;
returnZeroadd($bawtryReturnCount, $bawtryFReturnCount);

Accessing an array that is not inside class

I'd like to access an array which does not exist inside my Class, it seems like I can seems to do it, here's an example:
$chiInfo =
array(
array("Home", "#"),
array("Test", "#"),
);
class chiBar {
var $chiDet;
function __construct($chiName)
{
$this->chiDet = $chiName;
}
function getArrayData($array, $arrayNumber, $arrayType, &$result) // $arrayType : 1 - Non-multi, 2 - Multi
{
if(!is_array($array))
return 0;
if($arrayType == 1)
return 0;
else
{
if($arrayNumber > sizeof($array)-1)
{
print("Invalid array number!");
return 0;
}
$result = array(strval($array[$arrayNumber][0]), strval($array[$arrayNumber][1]));
}
}
function addToHeader($array, $addName, $addLink)
{
array_push($chiInfo, array($addName, $addLink)); // That is the link
echo "<META HTTP-EQUIV='refresh' CONTENT='15; URL=index.php'>";
}
}
Whenever I do a different piece of code, it seems like the array is not found, error:
Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\NewTest\navClass.php on line 40
Just pass that array as a parameter to the method:
function addToHeader($chiInfo, $array, $addName, $addLink)
And then when you call it:
$chiBar = new chiBar($chiName);
$chiBar->addToHeader($chiInfo, $array, $addName, $addLink);
If you would like to access a variable directly from your "top-level" code inside a function or class method, you must declare the variable global inside the function or method.
E.g.
...
function addToHeader($array, $addName, $addLink)
{
global $chiInfo;
array_push($chiInfo, array($addName, $addLink)); // That is the link
echo "<META HTTP-EQUIV='refresh' CONTENT='15; URL=index.php'>";
}
...
However, you may consider adding an extra parameter to your method instead, as globals can get tricky in some contexts. You can find out more about using globals here: http://php.net/manual/en/language.variables.scope.php
The same method using a parameter instead:
...
// note the ampersand on the parameter because you seem to want to change the original variable, not just a copy of it
function addToHeader($array, $addName, $addLink, &$chiInfo)
{
array_push($chiInfo, array($addName, $addLink)); // That is the link
echo "<META HTTP-EQUIV='refresh' CONTENT='15; URL=index.php'>";
}
...

passing a variable to callback function in codeigniter

In codeigniter what is the correct method of passing variables to the callback function?
I have used this,
$var1 = 'some conditions';
$this->form_validation->set_rules("callback__is_value_unique[value, $var1]");
public function _is_value_unique($value, $var1){
echo $var1;
die;
}
This gave me output like shown below:-
value, some conditions
rather than,
some conditions
You must only set your value!
$var1 = 'some conditions';
$this->form_validation->set_rules("callback__is_value_unique[value, $var1]");
public function _is_value_unique($value, $var1){
echo $var1;
die;
}
From the docs..
If you need to receive an extra parameter in your callback function,
just add it normally after the function name between square brackets,
as in: "callback_foo[bar]", then it will be passed as the second
argument of your callback function.
Sounds like you could only pass one extra argument. Which should be a string. If you want to pass more arguments, you could store them somewhere else and just pass an argument, which stores the location of the additional param.
$index = count($this->arguments);
$this->arguments[$index] = array('value', 'some conditions'/*, ...*/);
$this->form_validation->set_rules("callback__is_value_unique[$index]");
public function _is_value_unique($value, $index){
$args = $this->argumts[$index];
echo $args[1];
die;
}

Directly display the value of an array returned by a method

Is it possible to do in one line calling a method that returns an array() and directly get a value of this array ?
For example, instead of :
$response = $var->getResponse()->getResponseInfo();
$http_code = $response['http_code'];
echo $http_code;
Do something like this :
echo $var->getResponse()->getResponseInfo()['http_code'];
This example does not work, I get a syntax error.
If you're using >= PHP 5.4, you can.
Otherwise, you'll need to use a new variable.
What you can do is to pass the directly to your function. Your function should be such that if a variable name is passed to it, it should the value of that variable, else an array with all variables values.
You can do it as:
<?php
// pass your variable to the function getResponseInfo, for which you want the value.
echo $var->getResponse()->getResponseInfo('http_code');
?>
Your function:
<?php
// by default, it returns an array of all variables. If a variable name is passed, it returns just that value.
function getResponseInfo( $var=null ) {
// create your array as usual. let's assume it's $result
/*
$result = array( 'http_code'=>200,'http_status'=>'ok','content_length'=>1589 );
*/
if( isset( $var ) && array_key_exists( $var, $result ) ) {
return $result[ $var ];
} else {
return $result;
}
}
?>
Hope it helps.
Language itself does not support that for an array.
In case you can change what getResponseInfo() return:
You can create simple class, which will have array as an constructor parameter. Then define magical getter which will be just pulling the keys from the instance array
function __get($key)
{
return #content[$key]
}
Then you'll be able to do
echo $var->getResponse()->getResponseInfo()->http_code;
// or
echo $var->getResponse()->getResponseInfo()->$keyWhichIWant;
What i wrote is just proposal. The real __get method should have some check if the exists and so

I have a method which only needs to be executed once in PHP but will be called twice. How do I structure this?

I have a method in PHP which calls a SOAP service, parses some data and returns it.
It will return the same data - it asks how many records in a data object.
I need to call it twice with a pass.
My question is, what is best practice for structuring this in PHP? I've tried to see if the function has been called already.Do I use static variables / functions?
function MinimumRequired() {
return $this->NumberPeopleJoined();
}
function NumberPeopleJoined () {
if (isset($NumberPeople)) {
Debug::Show($NumberPeople);
}
static $NumberPeople;
$NumberPeople = Surge_Controller::NumberPeopleJoined();
return $NumberPeople;
}
Thanks!
Just create a local class member, and check if that has a value. If not, set the value to whatever is retrieved from Surge_Controller, and if it was already set, just return the value:
<?php
class Surge_Controller {
static public function NumberPeopleJoined() {
echo "Surge_Controller::NumberPeopleJoined() got called.\n";
return 2;
}
}
class Foo {
protected $cacheNumberPeople;
function MinimumRequired() {
return $this->NumberPeopleJoined();
}
function NumberPeopleJoined () {
if( !isset( $this->cacheNumberPeople ) ) {
$this->cacheNumberPeople = Surge_Controller::NumberPeopleJoined();
}
return $this->cacheNumberPeople;
}
}
$foo = new Foo( );
echo $foo->numberPeopleJoined( ) . "\n";
echo $foo->numberPeopleJoined( ) . "\n";
Output:
$ php foo.php
Surge_Controller::NumberPeopleJoined() got called.
2
2
The simple way is to have a global variable, and check if is "true", and set it to true at the end of your function. The value can be cached too...
But if you want to make your code fun, you can use underscore:
http://brianhaveri.github.com/Underscore.php/#once
http://brianhaveri.github.com/Underscore.php/#memoize

Categories