Is there anyway I can unset (and set a new value) for a variable in a core class of a script without touching the core code?
This is how the value of the variable set in the class:
class MyClass {
var $myvar = 'value';
...
...
}
I tried this, but didn't worked;
function unset_myvar($myvar) {
unset($myvar);
$myvar = 'newvalue';
return $myvar;
}
Thanks
Instead:
$myvar = 'newvalue';
you are looking for
$this->myvar = 'newvalue';
You are asking elementary question, so I suggest instead of just copying lines from my answer, you now head to PHP.net and read manual about PHP fundamentals
Try this:
class MyClass {
var $myvar = 'value';
function unset_myvar($myvar) {
unset($this->myvar);
$this->myvar = $myvar;
return $this->myvar;
}
}
So, now you can creat and object and unset variable and set another value to it:
$obj = MyClass ();
$obj = unset_myvar('someValue');
Simply:
class MyClass {
public $myvar = 'value';
...
...
}
$obj = new MyClass();
unset($obj->myvar);
The following code prints the value which was assigned , unsets the variable and then sets a new value to the variable.
<?php
class MyClass {
var $myvar = 'value';
public function dispvar()
{
echo $this->myvar;
}
public function destroyvar()
{
unset($this->myvar);
}
public function setvar($param)
{
$this->myvar=$param;
}
}
$a = new MyClass();
$a->dispvar(); //"prints" value
$a->destroyvar();
$a->dispvar(); //"prints" nothing !!
$a->setvar('blabla');
$a->dispvar(); //"prints" blabla
Demo
Related
How can I create a property from a given argument inside a object's method?
class Foo{
public function createProperty($var_name, $val){
// here how can I create a property named "$var_name"
// that takes $val as value?
}
}
And I want to be able to access the property like:
$object = new Foo();
$object->createProperty('hello', 'Hiiiiiiiiiiiiiiii');
echo $object->hello;
Also is it possible that I could make the property public/protected/private ? I know that in this case it should be public, but I may want to add some magik methods to get protected properties and stuff :)
I think I found a solution:
protected $user_properties = array();
public function createProperty($var_name, $val){
$this->user_properties[$var_name] = $val;
}
public function __get($name){
if(isset($this->user_properties[$name])
return $this->user_properties[$name];
}
do you think it's a good idea?
There are two methods to doing it.
One, you can directly create property dynamically from outside the class:
class Foo{
}
$foo = new Foo();
$foo->hello = 'Something';
Or if you wish to create property through your createProperty method:
class Foo{
public function createProperty($name, $value){
$this->{$name} = $value;
}
}
$foo = new Foo();
$foo->createProperty('hello', 'something');
The following example is for those who do not want to declare an entire class.
$test = (object) [];
$prop = 'hello';
$test->{$prop} = 'Hiiiiiiiiiiiiiiii';
echo $test->hello; // prints Hiiiiiiiiiiiiiiii
Property overloading is very slow. If you can, try to avoid it. Also important is to implement the other two magic methods:
__isset();
__unset();
If you don't want to find some common mistakes later on when using these object "attributes"
Here are some examples:
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
EDITED after Alex comment:
You can check yourself the differences in time between both solutions (change $REPEAT_PLEASE)
<?php
$REPEAT_PLEASE=500000;
class a {}
$time = time();
$a = new a();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
$a->data = 'bye'.$a->data;
}
echo '"NORMAL" TIME: '.(time()-$time)."\n";
class b
{
function __set($name,$value)
{
$this->d[$name] = $value;
}
function __get($name)
{
return $this->d[$name];
}
}
$time=time();
$a = new b();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
//echo $a->data;
$a->data = 'bye'.$a->data;
}
echo "TIME OVERLOADING: ".(time()-$time)."\n";
Use the syntax: $object->{$property}
where $property is a string variable and
$object can be this if it is inside the class or any instance object
Live example: http://sandbox.onlinephpfunctions.com/code/108f0ca2bef5cf4af8225d6a6ff11dfd0741757f
class Test{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$test = new Test();
$test->createProperty('property1', '50');
echo $test->property1;
Result: 50
This question may sound stupid, but I want this to work. I've got this code:
$data['method'] = 'get';
$this->app->$data['method']();
How can I replace $data['method'] with get but no string. I've tried this, but no luck.
$this->app->{$data['method']}();
Any idea?
The last code you posted should work, if you're using PHP 5.4.0 and higher.
<?php
class A {
public function foo() {
echo "yes!";
}
}
class B {
public function run() {
$this->a = new A;
$data = [];
$data['method'] = "foo";
$this->a->{$data['method']}();
}
}
$b = new B;
$b->run();
// Prints "yes!"
This will work:
call_user_func(array($this->app, $data['method']));
good luck.
How can I create a property from a given argument inside a object's method?
class Foo{
public function createProperty($var_name, $val){
// here how can I create a property named "$var_name"
// that takes $val as value?
}
}
And I want to be able to access the property like:
$object = new Foo();
$object->createProperty('hello', 'Hiiiiiiiiiiiiiiii');
echo $object->hello;
Also is it possible that I could make the property public/protected/private ? I know that in this case it should be public, but I may want to add some magik methods to get protected properties and stuff :)
I think I found a solution:
protected $user_properties = array();
public function createProperty($var_name, $val){
$this->user_properties[$var_name] = $val;
}
public function __get($name){
if(isset($this->user_properties[$name])
return $this->user_properties[$name];
}
do you think it's a good idea?
There are two methods to doing it.
One, you can directly create property dynamically from outside the class:
class Foo{
}
$foo = new Foo();
$foo->hello = 'Something';
Or if you wish to create property through your createProperty method:
class Foo{
public function createProperty($name, $value){
$this->{$name} = $value;
}
}
$foo = new Foo();
$foo->createProperty('hello', 'something');
The following example is for those who do not want to declare an entire class.
$test = (object) [];
$prop = 'hello';
$test->{$prop} = 'Hiiiiiiiiiiiiiiii';
echo $test->hello; // prints Hiiiiiiiiiiiiiiii
Property overloading is very slow. If you can, try to avoid it. Also important is to implement the other two magic methods:
__isset();
__unset();
If you don't want to find some common mistakes later on when using these object "attributes"
Here are some examples:
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
EDITED after Alex comment:
You can check yourself the differences in time between both solutions (change $REPEAT_PLEASE)
<?php
$REPEAT_PLEASE=500000;
class a {}
$time = time();
$a = new a();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
$a->data = 'bye'.$a->data;
}
echo '"NORMAL" TIME: '.(time()-$time)."\n";
class b
{
function __set($name,$value)
{
$this->d[$name] = $value;
}
function __get($name)
{
return $this->d[$name];
}
}
$time=time();
$a = new b();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
//echo $a->data;
$a->data = 'bye'.$a->data;
}
echo "TIME OVERLOADING: ".(time()-$time)."\n";
Use the syntax: $object->{$property}
where $property is a string variable and
$object can be this if it is inside the class or any instance object
Live example: http://sandbox.onlinephpfunctions.com/code/108f0ca2bef5cf4af8225d6a6ff11dfd0741757f
class Test{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$test = new Test();
$test->createProperty('property1', '50');
echo $test->property1;
Result: 50
I want to know how many instances of a particular class are present in memory.
class Test
{
public function testFunction() { return 'Test'; }
}
I create some objects:
$test1 = new Test();
$test2 = new Test();
$test3 = new Test();
How can I count the number of Test objects?
You can implement this using a static variable in your class, which you keep updated via it's constructor and destructor. Here is how:
class MyClass {
public static $instanceCount = 0;
function __construct() {
self::$instanceCount++;
}
function __destruct() {
self::$instanceCount--;
}
}
// create 3 instances
$a = new MyClass();
$b = new MyClass();
$c = new MyClass();
echo MyClass::$instanceCount; // outputs: 3
// implicitly lose one instance (destructor is called)
$a = "test";
echo MyClass::$instanceCount; // outputs: 2
You can try get_defined_vars function
It returns an array with defined vars, then you'll need to loop through the array an count by class. To get the class of a given variable you can use get_class function.
Maybe something like this:
function countVars() {
$varsDefined = [];
foreach(get_defined_vars() as $v) {
$varClass = get_class($v);
if (!isset($varsDefined[$varClass])) $varsDefined[$varClass] = 0;
$varsDefined[$varClass]++;
}
return $varsDefined;
}
I couldĀ“t test the code so it could have some mistakes, but I think the idea is there :)
Hope it helps!
Does anyone know how to reset the instance variables via a class method. Something like this:
class someClass
{
var $var1 = '';
var $var2 = TRUE;
function someMethod()
{
[...]
// this method will alter the class variables
}
function reset()
{
// is it possible to reset all class variables from here?
}
}
$test = new someClass();
$test->someMethod();
echo $test->var1;
$test->reset();
$test->someMethod();
I know I could simply do $test2 = new SomeClass() BUT I am particularly looking for a way to reset the instance (and its variables) via a method.
Is that possible at all???
You can use reflection to achieve this, for instance using get_class_vars:
foreach (get_class_vars(get_class($this)) as $name => $default)
$this -> $name = $default;
This is not entirely robust, it breaks on non-public variables (which get_class_vars does not read) and it will not touch base class variables.
Yes, you could write reset() like:
function reset()
{
$this->var1 = array();
$this->var2 = TRUE;
}
You want to be careful because calling new someClass() will get you an entirely new instance of the class completely unrelated to the original.
this could be easy done;
public function reset()
{
unset($this);
}
Sure, the method itself could assign explicit values to the properties.
public function reset()
{
$this->someString = "original";
$this->someInteger = 0;
}
$this->SetInitialState() from Constructor
Just as another idea, you could have a method that sets the default values itself, and is called from within the constructor. You could then call it at any point later as well.
<?php
class MyClass {
private $var;
function __construct() { $this->setInitialState(); }
function setInitialState() { $this->var = "Hello World"; }
function changeVar($val) { $this->var = $val; }
function showVar() { print $this->var; }
}
$myObj = new MyClass();
$myObj->showVar(); // Show default value
$myObj->changeVar("New Value"); // Changes value
$myObj->showVar(); // Shows new value
$myObj->setInitialState(); // Restores default value
$myObj->showVar(); // Shows restored value
?>