I need a function that will take a string as an argument, then check to see if a variable named the same thing as that string is set.
This works...
$foo = 'foosuccess';
$property = 'foo';
if(isset($$property)){
echo $$property;
}
This doesn't, because within test(), $$property2 is the wrong scope.
$huh = 'huhsuccess';
$huh = test("huh");
function test($property2){
if(isset($$property2)){
echo $$property2;
}
}
How can I fix the function so $$property2 refers to the same scope as the caller's context? Is that possible?
Thanks in advance....
try this:
$huh = 'huhsuccess';
test("huh");
function test($property2) {
global $$property2;
if(isset($$property2)) {
echo $$property2;
}
}
<?php
function test($s)
{
return isset($GLOBALS[$s]);
}
ok, i think i figured it out for my purposes (if anyone's interested...)
//uncomment to get success
//$huh = 'huhsuccess';
$huh = test($huh);
echo $huh;
function test(&$property2) {
if(isset($property2)) {
return $property2;
} else {
return 'not set!';
}
}
die;
This can be done with eval():
$foo = 'foosuccess';
$property = 'foo';
if(eval('isset($'.$property.')'){
echo $$property;
}
Related
I cannot workout why this script always returns 0. If I change it to echo getSKU() it works, but Quantity, Price or Name never seems to work. If anybody has any ideas please, please help this is irritating the life out of me!
<?php
session_start();
$sku = "0001";
if (!isset($_SESSION[$sku])) {
$_SESSION[$sku] = new product($sku, 5);
} else {
}
echo $_SESSION[$sku]->getQuantity();
class product {
var $sku;
var $name;
var $price;
var $quantity;
function __construct($par1, $par2) {
$this->sku = $par1;
$this->quantity = $par2;
}
function setSKU($x) {
$this->sku = $x;
}
function getSKU() {
echo $this->sku;
}
function setName($x) {
$this->name = $x;
}
function getName() {
echo $this->name;
}
function setPrice($x) {
$this->price = $x;
}
function getPrice() {
echo $this->price;
}
function setQuantity($x) {
$this->quantity = $x;
}
function incrementQuantity() {
$this->quantity++;
}
function getQuantity() {
echo $this->quantity;
}
}
You should use return instead of echo. Your get...-methods currently don't return something (just implicitly null), they just echo the value you want to return.
To fix this, just replace in every get...-method echo with return - i.e.
function getQuantity() {
return $this->quantity;
}
In addition to that, you should know, that you cant store objects in $_SESSION (actually you could, but then you have to implement the magic __sleep and __wakeup-methods..).
You should think about other solutions to store your products inside the session (i.e. serialize them)
you shouldn't echo your attribute in get methodes
echo $this->Variable;
you should always return them.
return $this->Variable;
return returns program control to the calling module. Execution
resumes at the expression following the called module's invocation
for more information on return check the documentation here
while the issues brought up in the other answers should definitely be addressed, to answer your question i believe the quantity is probably not set. can you try adding this line?
$_SESSION[$sku]->setQuantity(5);
$_SESSION[$sku]->getQuantity();
Working on a project of translating website and I had chose this solution
.
I'm trying to accomplish something like :
$VAR1 = $translate->__('Word_To_Translate');
This, not works for me since, the result is directly shown in stdout of the webpage. Even so when trying to call $VAR1 no result is returned.
This is not easily possible with the class you've mentioned.
If you wish to edit the class so it'll return the value instead of echoing it, you can edit class.translation.php, replace the two occurances of echo $str; with return $str;, and replace echo $this->lang[$this->language][$str]; with return $this->lang[$this->language][$str] (simply changing echo to return on both instances).
//$VAR1 delegating
$VAR1 = $translate->__('Word_To_Translate');
//class.translation.php
`class Translator {
private $language = 'en';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
return $this->lang[$this->language][$str];
return;
}
return $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
return $str;
}
}
else {
return $this->findString($str);
}
}
}`
Switched the echo for a return
Thank you very much uri2x && Rizier123.
For the moment looks that it is working solution.
Best wishes !
Is PHP exists a function that detect the change of variable?
That is something like this:
//called when $a is changed.
function variableChanged($value) {
echo "value changed to " . $value;
}
$a = 1;
//attach the variable to the method.
$a.attachTo("variableChanged");
$a = 2;
$a = 3;
//expected output:
//value changed to 2
//value changed to 3
I know that it is easy to achieve if I use the "setter" method. But since I am working on some existing codes, I am not able to modify them. Can somebody tell me how to achieve my purpose? Thanks.
know that it is easy to achieve if I use the "setter" method. But since I am working on some existing codes, I am not able to modify them.
I assume that you can change some code, but not the object / class you are working with. If you cannot change any code at all this question would be useless.
What you can do is make your own class, extending the class you are working with, and adding your setter there. For all purposes you can not-override the parent setting, except for a magic setter on whatever you need to track. Track changes and then call the parent functions, so no changes in any other internal workings will be in effect.
This could only be achieved by wrapping your variable within a class, and implementing a onchange yourself.
ie.
class MyVarContainer {
var $internalVar = array();
function __get($name) {
return !empty($this->internalVar[$name]) $this->internalVar[$name] ? FALSE;
}
function __set($name, $value) {
$oldval = $this->$name;
$this->internalVar[$name] = $value;
if($oldval !== FALSE) {
onUpdated($name, $oldval, $value);
} else {
onCreated($name, $value);
}
}
function onCreated($name, $value) {
}
function onUpdated($name, $oldvalue, $newvalue) {
}
}
You could revised your code as simple like this just to produce that expected output you want.
function variableChanged($value) {
return "value changed to " . $value;
}
$a = 1;
echo $a = variableChanged(2);
echo '<br/>';
echo $a = variablechanged(3);
=================
//output
value changed to 2
value changed to 3
or using a class like this....
class VariableHandler{
private $Variable;
function setVariable($initialValue = NULL){
$this->Variable = $initialValue;
return $initialValue;
}
function changeValue($newValue = NULL){
$this->Variable = $newValue;
return "value has change to ". $newValue;
}
}
$var = new VariableHandler;
echo $a = $var->setVariable(1);
echo '<br/>';
echo $var->changeValue(2);
echo '<br/>';
echo $var->changeValue(3);
=================
//output
value changed to 2
value changed to 3
Besides using a debugger:
The SplObserver interface is used alongside SplSubject to implement
the Observer Design Pattern.
http://www.php.net/manual/en/class.splobserver.php
Or the magic methods __get() and __set(): Encapsulating the variable into a class, you could implement a event handler yourself and register the change of a variable. Also you could attach callbacks like here:
<?php
header("content-type: text/plain");
class WatchVar {
private $data = array();
private $org = array();
private $callbacks = array();
public function __set($name, $value) {
if (!array_key_exists($name, $this->data)) {
$this->org[$name] = $value;
} else {
//variable gets changed again!
$this->triggerChangedEvent($name, $value);
}
$this->data[$name] = $value;
}
public function &__get($name) {
if (array_key_exists($name, $this->data)) {
if ($this->data[$name] != $this->org[$name]) {
//variable has changed, return original
//return $this->org[$name];
//or return new state:
return $this->data[$name];
} else {
//variable has not changed
return $this->data[$name];
}
}
}
public function addCallback($name, $lambdaFunc) {
$this->callbacks[$name] = $lambdaFunc;
}
protected function triggerChangedEvent($name, $value) {
//$this->data[$name] has been changed!
//callback call like:
call_user_func($this->callbacks[$name], $value);
}
}
$test = new WatchVar;
$test->addCallback('xxx', function($newValue) { echo "xxx has changed to {$newValue}\n"; });
$test->xxx = "aaa";
echo $test->xxx . "\n";
//output: aaa
$test->xxx = "bbb";
//output: xxx has changed to bbb
echo $test->xxx . "\n";
//output bbb
function messyFunction(&$var) {
$var = "test";
}
messyFunction($test->xxx);
//output:
I'm trying to call a function with a php variable variable. You'll see in my code in function mainFunction(). If it's not possible to do it this way, is there a better way to do it, that avoids any more code? I wish it would work this way.
<?php
$a = 1;
$b = 1;
if ( $a == $b ) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction();
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$$exampleFunction();//Here's where I'm stuck.
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
?>
A way to solve this problem would be to use PHP's call_user_func function. Here is the modified code (it also removes the global variable):
Code Example
<?php
$a = 1;
$b = 1;
// I'm just using this to hold the function name,
// to get rid of the global keyword. It will be passed
// as an argument to our mainFunction()
$exampleFunction = '';
if ($a == $b) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction($exampleFunction);
function mainFunction($func) {
echo 'This is mainFunction <br>';
// Use PHP's call_user_func. We are also checking to make sure
// the function exists here.
if (function_exists($func)) {
// This will call the function.
call_user_func($func);
}
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
Output
When I run this code, it produces the following output:
This is mainFunction
This is example two
Try like
if ( $a == $b ) {
$exampleFunction = exampleOne();
} else {
$exampleFunction = exampleTwo();
}
and your functions should return like
function exampleOne() {
return 'This is example one <br>';
}
function exampleTwo() {
return 'This is example two <br>';
}
OR if you want to call them through the variable try to replace like
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Try with $exampleFunction(); instead of $$exampleFunction();
OR
use call_user_func($exampleFunction)
check this way :-
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Use just $exampleFunction, without $$:
<?php
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
?>
See manual of variable functions, not variable variables.
P.S.: Also, I suggest $exampleFunction to be an argument of mailFunction, rather than use globals.
<?php
class MaClasse
{
private $attributs = array();
private $unAttributPrive;
public function __get ($nom)
{
if (isset ($this->attributs[$nom]))
return $this->attributs[$nom];
}
public function __set ($nom, $valeur)
{
$this->attributs[$nom] = $valeur;
}
public function afficherAttributs()
{
echo '<pre>', print_r ($this->attributs, true), '</pre>';
}
}
$obj = new MaClasse;
$obj->attribut = 'Simple test';
$obj->unAttributPrive = 'Autre simple test';
echo $obj->attribut;
echo $obj->autreAtribut;
$obj->afficherAttributs();
?>
I don't understand why the second variable does not show anything?
But in the array it does exist.
You're setting unAttributPrive, but getting autreAtribut.
I'm gonna go out on a whim and guess because you are spelling your variable names wrong. If you are looking to echo $obj->unAttributPrive