access outside array variable inside class - php

I have an array. but I don't know how to access it inside a class.
below is my sample code.
<?php
$value[0]=11;
$value[1]=22;
$value[2]=33;
class test {
var $code1,$code2,$code3;
function __construct() {
$this->$code1 = $value[0];
$this->$code2 = $value[1];
$this->$code3 = $value[2];
echo $code1;
}
}

Read this.
And you can do any one of the following:
Pass the value into the constructor as a parameter (recommended option)
<?php
$value[0]=11;
$value[1]=22;
$value[2]=33;
class test {
var $code1,$code2,$code3;
function __construct($value) {
$this->code1 = $value[0];
$this->code2 = $value[1];
$this->code3 = $value[2];
echo $this->code1;
}
}
$obj = new test($value);
?>
Use the $GLOBALS array (docs)
<?php
$value[0]=11;
$value[1]=22;
$value[2]=33;
class test {
var $code1,$code2,$code3;
function __construct() {
$this->code1 = $GLOBALS['value'][0];
$this->code2 = $GLOBALS['value'][1];
$this->code3 = $GLOBALS['value'][2];
echo $this->code1;
}
}
$obj = new test;
?>
Use the global keyword (docs)
<?php
$value[0]=11;
$value[1]=22;
$value[2]=33;
class test {
var $code1,$code2,$code3;
function __construct() {
global $value;
$this->code1 = $value[0];
$this->code2 = $value[1];
$this->code3 = $value[2];
echo $this->code1;
}
}
$obj = new test;
?>
NOTES
I have corrected a couple of errors above.
You should use $this->code1 instead of $this->$code1. The second version is valid syntactically, but means something else. Consider the following example:
class myClass {
public $myVar = "My Var";
public $anotherVar = "Another Var";
function __construct () {
// creates a local variable to the constructor, called $myVar
// does NOT overwrite the value defined above for the object property
$myVar = "anotherVar";
echo $myVar; // echoes 'anotherVar'
echo $this->myVar; // echoes 'My Var'
echo $this->$myVar; // echoes 'Another Var'
}
}
Also, the above example illustrates the reason why you should use echo $this->code1; and not simply echo $code1;

Something like this:
class test
{
var $code1,$code2,$code3;
function __construct($input)
{
$this->code1 = $input[0];
$this->code2 = $input[1];
$this->code3 = $input[2];
}
}
[...]
$value[0]=11;
$value[1]=22;
$value[2]=33;
$test = new test($value);

Global variables aren't visible inside functions, unless you use the global keyword. e.g.:
// Global variable
$x = 5;
// Won't affect the global
function foo()
{
$x = 3;
}
// Will affect the global
function bar()
{
global $x;
$x = 2;
}
Note
However, in general, it's not a good idea to use global variables like this. It introduces dependencies, and makes your code harder to test and to debug. I suggest you pass the variable in as an argument to your constructor.

class test {
private $code1,$code2,$code3;
function __construct($value) {
$this->code1 = $value[0];
$this->code2 = $value[1];
$this->code3 = $value[2];
echo $this->code1;
}
}
Usage :
$test = new Test($value);

Related

Returning references with or without a function

Are there any actual difference between the two ways to get the value by reference?
Way 1
<?php
class foo {
public $value = 42;
public function &getValue() {
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->getValue();
// $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;
// prints the new value of $obj->value, i.e. 2.
?>
Way 2
<?php
class foo {
public $value = 42;
public function getValue() {
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->value;
$obj->value = 2;
echo $myValue;
?>
In both cases 2 is printed. So why does one need the getValue() function then? The first example is taken from the PHP Manual.
You need the first approach if class fields don't have a modifier 'public'. In this case you can't get a reference to the field outside the class. See example:
<?php
class foo
{
protected $value = 1;
public function setValue($value)
{
$this->value = $value;
}
public function &getValue()
{
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->getValue();
$obj->setValue(2);
echo $myValue;
?>

How return a value from one class function to another class function in PHP

I am trying to get the value of a varibale if a condition is tru from one class function to another class function.
Could you please let me know how do i do this(I am new to PHP.)
Code:
class ErrorList{
static function getErrorsSince($delay, $criteria = NULL) {
global $appsFeXref, $table_error,$table_error_dis, $table_occurrence, $table_status, $table_fe_parameters, $debugMode;
if ($criteria->isValid()){
$var1 = '123';
}
}
Class Error{
function initFromDb($initDetails = false) {
global $appsFeXref, $table_error, $table_status, $table_fe_parameters, $table_error_dis;
$details = ($initDetails)? ", s.last_time, s.last_time_origin, s.last_time_machine, s.last_time_text, s.last_time_peak, ed.comment ":"";
$test = $var1;
echo "$test";
}
Here you can see I need $var1 variable value from ErrorList class to Error class.
Thanks in advance.
Regards,
Tejesh.B
<?php
class ErrorList{
static function getErrorsSince($delay, $criteria = NULL) {
global $appsFeXref, $table_error,$table_error_dis, $table_occurrence, $table_status, $table_fe_parameters, $debugMode;
if ($criteria->isValid()){
$var1 = '123';
return $var1;
}
}
}
class Error{
function initFromDb($initDetails = false) {
global $appsFeXref, $table_error, $table_status, $table_fe_parameters, $table_error_dis;
$details = ($initDetails)? ", s.last_time, s.last_time_origin, s.last_time_machine, s.last_time_text, s.last_time_peak, ed.comment ":"";
$call_class = new ErrorList();
$get_val = $call_class->getErrorsSince();
$test = $get_val;
echo $test;
}
}
?>

Convert String To Object-Variable-Name?

i want to turn a simple string like that "response->dict->words" into a variable name that i can actually work with. I will give an example now. Lets assume the value of $response->dict->words is 67.
Example:
$var = "response->dict->words"
echo $$var; /* PRINT THE VALUE 67 FROM $response->dict->words*/
As you may notice i put an extra dollar sign before the $var because this should work, but it doesn't.
Can anyone help me with this?
class ClassOne {
public function test() {
return 'test';
}
}
class ClassTwo {
public function test2() {
return 'test2';
}
}
$one = new ClassOne();
$two = new ClassTwo();
$objects = array('one', 'two');
$methods = array('test', 'test2');
for ($i = 0; $i < count($objects); $i++) {
echo ${$objects[$i]}->$methods[$i]();
}
You can store classnames or method names as strings and later use them, or even store variable names, like here ${$objects} (variable variables), but you cannot store whole logic.
To evaluate whole logic, you have to use eval(), which is most probably bad idea
$var = "response->dict->words"
eval("?> <?php echo $".$var.";");
You can split your string and make the call as below:
class Response {
public $dict;
public function __construct() {
$this->dict = new stdClass();
$this->dict->words = 'words test';
}
}
$response = new Response();
$var = 'response->dict->words';
$elements = explode('->', $var);
echo ${$elements[0]}->$elements[1]->$elements[2];
Results into words test
Or, if you don't know the level of nesting the object call, you can perform the call in a foreach loop. When the loop exits, the last call will be available after it:
class Response {
public $dict;
public function __construct() {
$this->dict = new stdClass();
$this->dict->words = new stdClass();
$this->dict->words->final = 'test chained string';
}
}
$response = new Response();
$var = 'response->dict->words->final';
$elements = explode('->', $var);
foreach ($elements as $key => $element) {
if ($key == 0) {
$call = ${$element};
continue;
}
$call = $call->$element;
}
echo $call;
Results into: test chained string
There is a better way, why don't you cache the variable like
$var = $response->dict->words;

PHP how to detect the change of variable?

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:

get a list of all variables defined outside a class by user

i have something like this:
class foo
{
//code
}
$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable"; //create foo->otherVariable
i can get in class foo a list of all variables defined outside by user (newVariable, otherVariable,etc)? Like this:
class foo
{
public function getUserDefined()
{
// code
}
}
$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable"; //create foo->otherVariable
var_dump($var->getUserDefined()); // returns array ("newVariable","otherVariable");
Thanks!.
Yes, using get_object_vars() and get_class_vars():
class A {
var $hello = 'world';
}
$a = new A();
$a->another = 'variable';
echo var_dump(get_object_vars($a));
echo '<hr />';
// Then, you can strip off default properties using get_class_vars('A');
$b = get_object_vars($a);
$c = get_class_vars('A');
foreach ($b as $key => $value) {
if (!array_key_exists($key,$c)) echo $key . ' => ' . $value . '<br />';
}
What is your goal? Imo it's not very good practice (unless you really know what you are doing). Maybe it's good idea consider create some class property like "$parameters" and then create setter and getter for this and use it in this way:
class foo {
private $variables;
public function addVariable($key, $value) {
$this->variables[$key] = $value;
}
public function getVariable($key) {
return $this->variables[$key];
}
public function hasVariable($key) {
return isset($this->variables[$key]);
}
(...)
}
$var = new foo();
$var->addVariable('newVariable', 1);
$var->addVariable('otherVariable', "hello, im a variable");
And then you can use it whatever you want, for example get defined variable:
$var->getVariable('otherVariable');
To check if some var is already defined:
$var->hasVariable('someVariable')
get_class_vars() http://php.net/manual/en/function.get-class-vars.php
You question is not clear though.
$var->newVariable = 1;
there are two possible contex of above expression
1) you are accessing class public variables.
like
class foo
{
public $foo;
public function method()
{
//code
}
}
$obj_foo = new foo();
$obj_foo->foo = 'class variable';
OR
2) you are defining class variable runtime using _get and _set
class foo
{
public $foo;
public $array = array();
public function method()
{
//code
}
public function __get()
{
//some code
}
public function __set()
{
// some code
}
}
$obj_foo = new foo();
$obj_foo->bar= 'define class variable outside the class';
so in which context your question is talking about?

Categories