Accessing an array that is not inside class - php

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'>";
}
...

Related

Calling the same function within another via parameter

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]);
}

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);

How to tell if a param was passed assuming it was a constant?

I am using this code (note: HELLO_WORLD was NEVER defined!):
function my_function($Foo) {
//...
}
my_function(HELLO_WORLD);
HELLO_WORLD might be defined, it might not. I want to know if it was passed and if HELLO_WORLD was passed assuming it was as constant. I don't care about the value of HELLO_WORLD.
Something like this:
function my_function($Foo) {
if (was_passed_as_constant($Foo)) {
//Do something...
}
}
How can I tell if a parameter was passed assuming it was a constant or just variable?
I know it's not great programming, but it's what I'd like to do.
if a constant isn't defined, PHP will treat it as String ("HELLO_WORLD" in this case) (and throw a Notice into your Log-files).
You could do a check as follows:
function my_function($foo) {
if ($foo != 'HELLO_WORLD') {
//Do something...
}
}
but sadly, this code has two big problems:
you need to know the name of the constant that gets passed
the constand musn't contain it's own name
A better solution would be to pass the constant-name instead of the constant itself:
function my_function($const) {
if (defined($const)) {
$foo = constant($const);
//Do something...
}
}
for this, the only thing you have to change is to pass the name of a constant instead of the constant itself. the good thing: this will also prevent the notice thrown in your original code.
You could do it like this:
function my_function($Foo) {
if (defined($Foo)) {
// Was passed as a constant
// Do this to get the value:
$value = constant($Foo);
}
else {
// Was passed as a variable
$value = $Foo;
}
}
However you would need to quote the string to call the function:
my_function("CONSTANT_NAME");
Also, this will only work if there is no variable whose value is the same as a defined constant name:
define("FRUIT", "watermelon");
$object = "FRUIT";
my_function($object); // will execute the passed as a constant part
Try this:
$my_function ('HELLO_WORLD');
function my_function ($foo)
{
$constant_list = get_defined_constants(true);
if (array_key_exists ($foo, $constant_list['user']))
{
print "{$foo} is a constant.";
}
else
{
print "{$foo} is not a constant.";
}
}

array_search wrong argument datatype

I am playing around with this:
$sort = array('t1','t2');
function test($e){
echo array_search($e,$sort);
}
test('t1');
and get this error:
Warning: array_search(): Wrong datatype for second argument on line 4
if I call it without function like this, I got the result 0;
echo array_search('t1',$sort);
What goes wrong here?? thanks for help.
Variables in PHP have function scope. The variable $sort is not available in your function test, because you have not passed it in. You'll have to pass it into the function as a parameter as well, or define it inside the function.
You can also use the global keyword, but it is really not recommended. Pass data explictly.
You must pass the array as a parameter! Because the functions variables are different from globals in php!
Here is the fixed one:
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t2',$sort);
You cannot directly access global variables from inside functions.
You have three options:
function test($e) {
global $sort;
echo array_search($e, $sort);
}
function test($e) {
echo array_search($e, $GLOBALS['sort']);
}
function test($e, $sort) {
echo array_search($e, $sort);
} // call with test('t1', $sort);
take the $sort inside the function or pass $sort as parameter to function test()..
For e.g.
function test($e){
$sort = array('t1','t2');
echo array_search($e,$sort);
}
test('t1');
----- OR -----
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t1',$sort);

How to access a member variable of different function in a codeigniter controller

//first function
function insertdigit(){
$userdigit=5;
$flag = $this->usermodel->userdigitmodel($userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->insertdigit();
}
but i get {"result":true} goes back to the function? how to access a member variable in a different member function
Try to remove echo json_encode($value); in your code.
If you need to access a parameter in several functions on your controller, you have to create it outside your function so it will be available for all your controller functions.
So, in your case it should be something like this:
class Test extends Controller
{
private $userdigit; //here you can set a default value if necessary: private $userdigit = 5
function insertdigit(){
$this->userdigit=5;
$flag = $this->usermodel->userdigitmodel($this->userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $this->userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->userdigit;
}
}
This way your userdigit variable is available for all your functions. With $this you are telling PHP that you are trying to access something inside the class.
This link contain more and useful information: http://www.php.net/manual/en/language.oop5.properties.php
Is that what you really need?
A possible solution:
function insertdigit()
{
$userDigit = 5;
$flag = $this->usermodel->userdigitmodel($userDigit);
$value = array
(
'result' => $flag
);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo json_encode($value);
}
if ($flag == true)
{
return $userdigit;
}
else
{
}
}
//second function
function usedigit()
{
$data['userdigit'] = $this->insertdigit();
}
The above code, in insertdigit detects if there is an Ajax request and if so, it will echo out the json_encoded data. If you call it in an normal request, i.e. via usedigit it won't echo the json_encoded data (unless you are calling usedigit via an Ajax request).
Your question doesn't really explain what you are doing, so it's hard to explain a better solution, however, if you are trying to access a "variable" in more than one place, you should really separate your code so you have a single entry point for that variable.
Is your variable dynamic, or is it static?

Categories