Variable arrays in class context - php

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!

Related

PHP: pass global variable to finction?

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

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

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

Variable inside the link

Would someone be able to help me with some php.
I am new to this and I am trying to solve the puzzle.
I am trying to combine the input data that user has provided with the link so that final output displays record for the user whose regid was provided by user via input text field.
Here is some code I came up with that obviously does not work.
class Fields_View_Helper_FieldStats extends Fields_View_Helper_FieldAbstract
{
public function fieldStats($subject, $field, $value)
{
$userid = preg_replace(trim($value->value));
// create user's profile address using their username/userid
$stats = $userid;
echo '<div style="margin:0px auto;"><script type="text/javascript" src="http://e1.statsheet.com/embed/';
return $this->view->string()->chunk($value->value);
echo '/1/NuNes.js"></script></div>';
}
}
To concatenate a string in PHP do this (note the periods, which are doing the work)
$str = "Line 1 " . $somevar . " Line 2";
return $str
Issuing a return terminates your function. I would build one string inside a variable then return that variable
The return ends the method, because it returns the value to the caller.
<?php
function fn() {
return "bar";
}
echo fn(); // will output bar
function fn2() {
echo "foo";
return "bar";
}
echo fn2(); // will output foobar
function fn3() {
return "foo" . fn();
}
echo fn3(); // will output foobar as well
?>
And here's how you can connect those three lines in the code snippet you posted:
<?php
class Fields_View_Helper_FieldStats extends Fields_View_Helper_FieldAbstract
{
public function fieldStats($subject, $field, $value)
{
$userid = preg_replace(trim($value->value));
// create user's profile address using their username/userid
$stats = $userid;
return
'<div style="margin:0px auto;"><script type="text/javascript" src="http://e1.statsheet.com/embed/' .
$this->view->string()->chunk($value->value) .
'/1/NuNes.js"></script></div>'
;
}
}
?>
And here's how you can concatenate strings:
<?php
$string1 = 'foo ' . fn() . ' bar';
$string2 = "foo 2" . fn() . " bar";
?>
And here's how you can embed stuff in variables (faster):
<?php
$string1 = fn();
$string1 = "foo {$string1} bar";
// Or with an object
class Foo {
public function fn(){}
}
$foo = new Foo();
$string1 = "foo {$foo->fn()} bar";
?>

PHP using inner function variable in another function

I tried this code today! But it's not giving the output I expected.. this is my code..
<?php
namePrint('Rajitha');
function namePrint($name) {
echo $name;
}
wrap('tobaco');
function wrap($txt) {
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>
This code will print on screen
RajithaYour username is tobaco
but I want to get
RajithaRajithaYour username is tobaco
My question is: why is the $name variable in the wrap function not working?
Thanks.
Never use echo inside function to output the result. And never use global for variables.
You used echo inside function and because of that you get unexpected output.
echo namePrint('Rajitha');
function namePrint($name){
return $name;
}
echo wrap('tobaco');
function wrap($txt){
//global $name;
return "Your username is ".namePrint('Rajitha')." ".$txt."";
}
Output using echo in function Codepad
RajithaRajithaYour username is tobaco
Output1 using return in function Codepad
RajithaYour username is Rajitha tobaco
If you want to wrap a function around another you could simply pass a closure as one of the arguments:
function wrap($fn, $txt)
{
echo "Your username is ";
$fn();
echo ' ' . $txt;
}
wrap(function() {
namePrint('Rajitha');
}, 'tobaco');
This construct is very delicate; using function return values is more reliable:
function getFormattedName($name) {
return $name;
}
echo getFormattedName('Jack');
Then, the wrap function:
function wrap($fn, $txt)
{
return sprintf("Your username is %s %s", $fn(), $txt);
}
echo wrap(function() {
return getFormattedName('Jack');
}, 'tobaco');
Another option would be to pass $name as a parameter to the wrap function.
<?php
$name = 'Rajitha';
function namePrint($name){
echo $name;
}
function wrap($txt, $name){
echo "Your username is " . $name . " ". $txt;
}
namePrint($name);
wrap('tobaco', $name);
?>
$name should be declared and initialized as global variable.then you can the output you need.
The code should look like this.
<?php
$name = 'Rajitha';
namePrint($name);
function namePrint($name){
echo $name;
}
wrap('tobaco');
function wrap($txt){
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>

Categories