How to dynamically assign a value to a class property in PHP? - php

I would like to assign a value in a class property dynamically (that is referring to it using a variable).
#Something like:
setPropValue($obj, $propName, $value);

$obj->$propName = $value;

In case you want to do this for static members, you can use variable variables:
class Foo
{
public static $foo = 'bar';
}
// regular way to get the public static class member
echo Foo::$foo; // bar
// assigning member name to variable
$varvar = 'foo';
// calling it as a variable variable
echo Foo::$$varvar; // bar
// same for changing it
Foo::$$varvar = 'foo';
echo Foo::$$varvar; // foo

Like this?
$myClass = new stdClass();
$myProp = 'foo';
$myClass->$myProp = 'bar';
echo $myClass->foo; // bar
echo $myClass->$myProp; // bar

Related

Access static object property through variable name

I know its possible to access an object property/method using a variable as its name
ex.:
$propName = 'something';
$something = $object->$propName;
Is it possible to do the same w/ constants or static properties?
I've tried:
$constName = 'MY_CONST';
MyCLass::{$constName};
and
$obj::{$constName};
But nothing seems to work and I couldn't find it anywhere.
Use: Class::$$constName, this is similar to normal variable variables.
Demo:
<?php
class MyClass {
public static $var = 'A';
}
$name = 'var';
echo MyClass::$$name; // echoes 'A'
Constants can be access with the constant function:
constant('MyClass::'.$constantName)
This works for me:
<?php
class Test {
public static $nombre = "pepe";
public function __construct() {
return self;
}
}
$varName = "nombre";
echo Test::${$varName};
You can use the constant function:
constant('bar::'. $const);
constant("$obj::". $const); //note the double quote

Is it possible to change a property of a class outside of the class? (PHP)

I'm quite inexperienced with OOP PHP but here's my question...let's say I have this class with one property:
class myClass {
public $property = array();
public function getProperty() {
return $this->property;
}
}
How would it be possible to change the value of $property without altering the class itself in any way, or by instantiating an object out of it, then changing its property. Is there any other way of doing it? Using scope resolution?
Hope that makes sense, any help would be much appreciated.
What you want is a static member
class MyClass {
public static $MyStaticMember = 0;
public function echoStaticMember() {
echo MyClass::$MyStaticMember;
//note you can use self instead of the class name when inside the class
echo self::$MyStaticMember;
}
public function incrementStaticMember() {
self::$MyStaticMember++;
}
}
then you access it like
MyClass::$MyStaticMember = "Some value"; //Note you use the $ with the variable name
Now any instances and everything will see the same value for whatever the static member is set to so take for instance the following
function SomeMethodInAFarFarAwayScript() {
echo MyClass::$MyStaticMember;
}
...
MyClass::$MyStaticMember++; //$MyStaticMember now is: 1
$firstClassInstance = new MyClass();
echo MyClass::$MyStaticMember; //will echo: 1
$firstClassInstance->echoStaticMember(); //will echo: 1
$secondInstance = new MyClass();
$secondInstance->incrementStaticMember(); // $MyStaticMember will now be: 2
echo MyClass::$MyStaticMember; //will echo: 2
$firstClassInstance->echoStaticMember(); //will echo: 2
$secondInstance->echoStaticMember(); //will echo: 2
SomeMethodInAFarFarAwayScript(); //will echo: 2
PHPFiddle
I hope this is what you are looking for
<?php
class myClass {
public $property = array();
public function getProperty() {
print_r($this->property);
}
}
$a = new myClass();
$x = array(10,20);
$a->property=$x; //Setting the value of $x array to $property var on public class
$a->getProperty(); // Prints the array 10,20
EDIT :
As others said , yes you need the variable to be declared as static (if you want to modify the variable without creating new instance of the class or extending it)
<?php
class MyClass {
public static $var = 'A Parent Val';
public function dispData()
{
echo $this->var;
}
}
echo MyClass::$var;//A Parent Val
MyClass::$var="Replaced new var";
echo MyClass::$var;//Replacced new var
?>

Why does this not make a difference between property and variable?

class someclass
{
public $foo = 'abcd';
public function __construct($data)
{
$this->foo = $data;
}
public function doSomething()
{
$user = $_POST['username'];
echo $foo = $_POST['foo']; // This output correct value
var_dump($foo); // This Output NULL
$somethingelse = $_POST['foo'];
var_dump($somethingelse); // Output as expected
}
}
If i change my variable name or property name from $foo to something else in do in doSomething() it runs fine.
Why do I need to keep the property name and variable name different here?
Why does $foo is NULL when one of the property name is $foo?
You need to use $this->foo to get and set the classes property
change this
echo $foo = $_POST['foo'];
to
echo $this->foo = $_POST['foo'];
var_dump($this->foo);
When accessing class variables you need to use the $this-> prefix.
Change your code to
echo $this->foo = $_POST['foo'];
var_dump($this->foo);
It is correct and it works fine. I ran your code and it always gives me the same. There's no problem you have property $foo and $foo variable in one or multiple functions. It always give me the same answer.
If $_POST['foo']=test then echo $foo = $_POST['foo']; returns "test", $foo returns "test" and $somethingelse returns "test";

Using a define (or a class constant) to call a variable method?

Is it possible to :
define('DEFAULT_METHOD', 'defaultMethod');
class Foo
{
public function defaultMethod() { }
}
$foo = new Foo();
$foo->DEFAULT_METHOD();
Or do I have to :
$method = DEFAULT_METHOD;
$foo->$method();
And what about a class constant instead of a define ?
If you use a variable or constant as the method name, you have to put it into curly brackets:
$foo->{DEFAULT_METHOD}();
The same technique works for variables, including static class attributes:
class Foo {
public static $DEFAULT_METHOD = 'defaultMethod';
public function defaultMethod() { echo "Cool!\n"; }
}
$foo = new Foo();
$foo->{FOO::$DEFAULT_METHOD}();
In fact, practically any expression that results in a valid method name could be used:
$foo->{'default'.'Method'}();
You could set it to a variable first as in your example :)
Example: http://codepad.org/69W4dYP1
<?php
define('DEFAULT_METHOD', 'defaultMethod');
class Foo {
public function defaultMethod() { echo 'yay!'; }
}
$foo = new Foo();
$method = DEFAULT_METHOD;
$foo->$method();
?>

Simple PHP classes question

So I have:
class foo {
public $variable_one;
public $variable_two;
function_A(){
// Do something
$variable_one;
$variable_two;
// If I define variable_3 here!
$variable_3
// Would I be able to access it in function_B?
}
function_B(){
// Do something
$variable_4 = $variable_3
}
}
$myObj = new foo();
// Now what do I write in order to assign "variable_one" and "two" some value?
$myObj->$variable_one = 'some_value' ??
$myObj->$variable_two = 'some_value' ??
First, when you write simply $variable_one; inside A() it does not refer to the member variables of your class! That would be a completely different, newly created local variable called $variable_one bearing no relation to the class variable.
Instead, you want:
function A() {
$this->variable_one;
}
Second, your $variable_3 is also a local variable, and will not be accessible in any other function.
Third, your assignments at the bottom are correct in form, but not in syntax: there's an extra $ in there. You want:
$myObj->variable_one = 'some value';
No, $variable_3 was created (and will be destroyed) in the scope of function_A. This is due to function scope.
http://us3.php.net/manual/en/language.variables.scope.php
If you would like $variable_3 to be retained by your object once execution leaves function_A's scope, you need to assign it as a class property, similar to $variable_1 and $variable2.
class YourClass
{
public $variable_1;
public $variable_2;
public $variable_3;
function_A()
{
$this->variable_3 = "some value"; // assign to the object property
$variable_4 = "another value"; // will be local to this method only
}
function_B()
{
echo $this->variable_3; // Would output "some value"
echo $variable_4; // var does not exist within the scope of function_B
}
}
$myObj->variable_one = aValue;
$myObj->variable_two = anotherValue;
The correct code would be the following (see answer within comments)
class foo {
public $variable_one;
public $variable_two;
private $variable_three; // private because it is only used within the class
function _A(){
// using $this-> because you want to use the value you assigned at the
// bottom of the script. If you do not use $this-> in front of the variable,
// it will be a local variable, which means it will be only available inside
// the current function which in this case is _A
$this->variable_one;
$this->variable_two;
// You need to use $this-> here as well because the variable_3 is used in
// function _B
$this->variable_3;
}
function _B(){
// Do something
$variable_4 = $this->variable_3
}
}
$myObj = new foo();
$myObj->variable_one = 'some_value1'; // Notice no $ in front of the var name
$myObj->variable_two = 'some_value2'; // Notice no $ in front of the var name
Class variables (properties) must be accessed using the $this-> prefix, unless they are static (in your example they aren't). If you do not use the prefix $this-> they will be local variables within the function you define them.
I hope this helps!
If variable_one and variable_two are public, you can assign them as you specified (just remove the "$"...so $classObject->variable_one). Typically you want to encapsulate your variables by making them either protected or private:
class MyClass
{
protected $_variable_one;
public function getVariableOne()
{
return $this->_variable_one;
}
public function setVariableOne($value)
{
$this->_variable_one = $value;
}
}
$c = new MyClass();
$c->setVariableOne("hello!");
echo $c->getVariableOne(); // hello!

Categories