PHP: pass global variable to finction? - php

There is code:
<?php
$pamiClient = new PamiClient($options);
$pamiClient->open();
$temp = 42;
$pamiClient->registerEventListener(
function (EventMessage $event )
{
if ($event instanceof VarSetEvent) {
if ($varName == 'CALLID') {
$temp = 43;
echo "Temp from CALLID: " , $temp, "\n";
}
if ($varName == 'BRIDGEPEER') {
echo "Temp from BRIDGPEER: " , $temp, "\n";
}
}
}
);
while(true) {
$pamiClient->process();
usleep(1000);
}
$pamiClient->close();
?>
How to pass $temp to function (EventMessage $event), so changes are made in
if ($varName == 'CALLID'){} -section may be seen in if ($varName == 'BRIDGEPEER') {} section ?

You can inherit variables from the parent scope with use, for example:
function (EventMessage $event ) use ($temp)
{
// to do something
}

Use global.
For example:
<?php
$varName = "foo";
function test() {
global $varName;
if ($varName == "foo") { ... }
}
Read more: https://www.php.net/manual/en/language.variables.scope.php

Related

Variable arrays in class context

I am trying to accomplish a simple class method where the user submit its name to a form and it returns a greeting message for every name on the variable array, such as "Welcome John", "Welcome Mike", etc...
Doing this as a regular function is easy:
$arr = array('Mike', 'John', 'Molly', 'Louis');
function Hello($arr) {
if(is_array($arr)) {
foreach($arr as $name) {
echo "Hello $name" . "<br>";
}
} else {
echo "Hello $arr";
}
}
Hello($arr);
However, I can't make it work in class context:
$arr = array('Mike', 'John', 'Molly', 'Louis');
class greetUser {
public $current_user;
function __construct($current_user) {
$this->current_user = $current_user;
}
public function returnInfo() {
if(is_array($this->current_user)) {
foreach($this->current_user as $name) {
echo "Welcome, " . $name;
}
} else {
echo "Welcome, " . $this->current_user;
}
}
}
$b = new greetUser(''.$arr.'');
$b->returnInfo();
replace your $b = new greetUser(''.$arr.''); with $b = new greetUser($arr); and it will work :)
I was commiting a very silly mistake, as users pointed out, I was concatenating the variable when it was not necessary!

if else if condition not working properly

Test.php
<?php
$a = 'D:/mydomain/Slim/Lib/Table.php';
$b = '\Slim\Lib\Table';
foreach (array($a, $b) as $value)
{
if (file_exists($value))
{
echo "file_exist";
include_once($value);
new Table();
}
else if (class_exists($value))
{
echo "class_exist";
$class = new $value();
}
else
{
echo "error";
}
}
?>
and D:/mydomain/Slim/Lib/Table.php
<?php
class Table {
function hello()
{
echo "test";
}
function justTest()
{
echo "just test";
}
}
?>
When im execute test.php in browser the output result is:
file_exist
Fatal error: Cannot redeclare class Table in D:/mydomain/Slim/Lib/Table.php on line 2
if statement for class_exist is not trigger. namespace \Slim\Lib\Table is never exist.
The second, optional, parameter of class_exists is bool $autoload = true, so it tries to autoload this class. Try to change this call to class_exists( $value, false) See the manual.
The first if can be changed to:
if(!class_exists($value) && file_exists($file)
actually there are other problems:
$a = 'D:/mydomain/Slim/Lib/Table.php';
$b = 'Table'; //Since you don't have a namespace in the Table class...
//This ensures that the class and table are a pair and not checked twice
foreach (array($a=>$b) as $file=>$value)
{
if (!class_exists($value) && file_exists($file))
{
echo "file_exist";
include_once($file);
$class = new $value();
}
else if (class_exists($value))
{
echo "class_exist";
$class = new $value();
}
else
{
echo "error";
}
}

How can I access a variable inside another function?

I have two functions that print some values. I need to use the variable $mv in the second function. However, $mv can only be defined in the first function. I have tried all types of PHP global examples and none of them has allowed the $mv variable to be used or visible or accessible in the second function.
function printMobilePrev(&$mobileprevresults) {
if (count($mobileprevresults->getRows()) > 0) {
$mv = $mobileprevRows[0][0];
$mobileprevRows = $mobileprevresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
} else {
print '<p>No results found.</p>';
}
}
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
$mobdiff = ($mobcur - $mv);
$mobpctchg = ($mobdiff / $mobprev) * 100;
$mobilecurrRows = $mobilecurrresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
echo '<p>Previous period (sessions): '.$mv.'..............................';
echo '<p>Current period (sessions): '.$mobilecurrRows[0][0].'..............................';
if ($mobdiff > 0){
echo '<p>Percent increase: '.$mobpctchg.'..............................';
} else {
echo '<p>Percent decrease: '.$mobpctchg.'..............................';
}
} else {
print '<p>No results found.</p>';
}
}
You can use the global scope:
That is what you want to do:
$mv = 0;
function function1()
{
global $mv;
$mv = 'whatever';
//code
}
function function2()
{
global $mv;
// use $mv;
}
You have to predefine that variable OUTSIDE any function, and then you can use Global to get that to any function.
You can pass it by reference. For example
function doSomething(&$mv) {
$mv = 1;
}
function doSomethingElse($mv) {
return $mv;
}
$mv = 0;
doSomething($mv);
echo doSomethingElse($mv); //Output: 1
You could return $mv after your print and save that in a var to pass to the next function:
$printMobilePrev = printMobilePrev();
function printMobilePrev(&$mobileprevresults) {
$mv = $mobileprevRows[0][0];
...
print '<p>No results found.</p>';
return $mv;
...
}
$printMobileCurr = printMobileCurr(&$mobilecurrresults,$mv);
function printMobileCurr(&$mobilecurrresults,$mv) {
......
}
Most likely you have to make a correct use of globals.
declare your $mv variable as global before asigning it a value on your first function
global $mv;
$mv = $mobileprevRows[0][0];
use global at the begining on your second function before using it
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
global $mv;

How to quickly check what variables exist from a bunch of vars?

If you have 10 variables that are sometimes set, other times unset, is there a quick way to echo the ones that exist without throwing an exception? These vars come from user input.
I would currently write it as
if ($var_1 != NULL) { echo $var_1; }
if ($var_2 != NULL) { echo $var_2; }
if ($var_3 != NULL) { echo $var_3; }
if ($var_other_1 != NULL) { echo $var_other_1 ; }
if ($var_other_2 != NULL) { echo $var_other_2 ; }
etc.. But is there a more quicker way?
compact function will help you
Check this function: http://php.net/manual/en/function.get-defined-vars.php
You can do something like this:
<?php
$vararr = get_defined_vars();
foreach ($vararr as $name => $value) {
echo "{$name}: {$value}<br>\n";
}
Here's another option using variable variables and a list of the variables you want to examine:
foreach( array("var_1", "var_2") as $var )
{
if( isset($$var) )
{
echo $$var;
}
}

PHP Namespace and Include() with classes

there is a project which I need to extend. All classes are in seperate files, I need to extend some of the classes without rewriting existing code in other files. My idea was to use namespaces but I fail. Here is an example:
I've renamed the original A.php class file to A_Original.php:
class A
{
public function hello()
{
echo "hello world from Class A\n";
}
}
Then created a new A.php:
namespace AOriginal {
include 'A_Original.php';
}
namespace {
class A
{
public function hello()
{
echo "hello world from Class A Extended\n";
}
}
}
This fails because on including the original A_Original.php file the class is dumped to the global scope (thus ignoring the namespace command).
I can not modify the existing code inthe A_Original.php file, but renaming is ok.
The other project files (whic I cannot modify) use a require "A.php".
How to accomplish this?
You can extend a class without modifying its existing behaviour:
class A {
public function foo(){
}
}
class MySubClassOfA extends A {
public function bar(){
}
}
You can add your own methods to MySubClassOfA, i.e. bar(). You can call the foo method on MySubClassOfA and it's behaviour is the same, unless you define a method called foo in MySubClassOfA.
I guess that you have no choice but add the single line of "namespace xxx;" code on top of all your files. The following PHP CLI script may be useful.
<?php
function convert($namespace, $srcdir, $dstdir)
{
try
{
$files = glob("$srcdir/{*,.*}", GLOB_BRACE);
if ( ! file_exists($dstdir) && ! mkdir($dstdir) )
{
throw new Exception("Cannot create directory {$dstdir}");
}
if ( ! is_dir($dstdir) )
{
throw new Exception("{$dstdir} is not a directory");
}
foreach ( $files as $f )
{
extract(pathinfo($f)); // then we got $dirname, $basename, $filename, $extension
if ( $basename == '.' || $basename == '..' )
{
continue;
}
if ( is_dir($f) )
{
$d = $dstdir. substr($f, strlen($srcdir));
convert($namespace, $f, $d);
continue;
}
print "processing {$f} ... ";
if ( ($s = file_get_contents($f)) === FALSE )
{
throw new Exception("Error reading $f");
}
if ( preg_match("/^\s*namespace\s+\S+;/m", $s) )
{
print "already has namespace, skip";
}
else
{
$lines = preg_split("/(\n|\r\n)/", $s);
$output = array();
$matched = FALSE;
foreach ( $lines as $s )
{
$output[] = $s;
// check if this is a PHP code?
if ( ! $matched && preg_match('/<(\?(php )*|%)/', $s) )
{
$matched = TRUE;
print "insert namespace ... ";
$output[] = "namespace {$namespace};";
}
}
if ( file_put_contents("{$dstdir}/{$basename}" , implode("\n", $output)) === FALSE )
{
throw new Exception("Cannot save file {$dstdir}/{$basename}");
}
if ( ! $matched )
{
print ("not a PHP file, skip.");
}
else
{
print "done!";
}
}
print "\n";
}
}
catch (Exception $e)
{
print 'Error: '. $e->getMessage() .' ('. $e->getCode() .')' ."\n";
}
}
extract($_SERVER);
if ( $argc < 4 )
{
?>
Usage: php -F <?=$argv[0]?> <namespace> <source_dir(s)> <dst_dir>
Convert PHP code to be namespace-aware
<?
return;
}
else
{
for ( $i = 2; $i < $argc - 1; $i++ )
{
convert($argv[1], $argv[$i], $argv[$argc-1]);
}
}
?>
How about eval()?
New A.php
$lines = file('a_original.php');
array_unshift($lines, 'namespace AO;?>');
$string = implode(chr(13).chr(10), $lines);
eval($string);
class A extends AO\A
{
public function hello()
{
parent::hello();
echo "hello world from Class A Extended\n";
}
}

Categories