Confused on how php objects handle arrays - php

The output of this is "24", when I'd expect "44".
class some_class {
public $array = array();
public function construct() {
$this->array[5] = 4;
}
public function something() {
// $this->array at this point is empty, why?
echo (isset($this->array[5])) ? $this->array[5] : 2;
$this->array[5] = 4;
// Here, $this->array holds the value 4 in the key 5 correctly
echo (isset($this->array[5])) ? $this->array[5] : 2;
}
}
$some_object = new some_class();
$some_object->something();
Any ideas why my expectations are being shattered?

Your constructor isn't firing it needs to be called:
public function __construct(){
// constructor
}
otherwise the array fails to initialize.

Your question basically boils down to your line at the beginning of something(), asking:
$this->array at this point is empty, why?
This is the case because PHP constructors need to be named __construct, whereas yours is simply named construct.

Your function construct() is never called. You should name it __construct().

Related

static variable in php closure defined within a private class method

So I re-wrote this to hopefully be clearer about what I'm attempting. During some parsing of data someValue(s) associated with someCode(s) are received. The intent is to capture a particularValue of a someCode having the lowest precedence, irrespective of the order the someCode/someValue (s) received. The issue keeping this from working is that the closure is created every time the private function is called and the value of $precedenceOfCodeCaptured therefore is always reset to null. If I could keep the closure around then things might work as intended.
private function Foo($particularValue, $someValue, $someCode) {
switch ($someCode) {
case:
CODE1:
case:
CODE2:
$c = function () use ($someCode, $someValue) {
static $precedenceOfCodeCaptured = null;
$precedenceArray = array(
CODE2 => 1,
CODE1 => 2
);
if ((is_null($someValue))) {//first time the case statement matched because $someValue==null
$precedenceOfCodeCaptured = $precedenceArray[$someCode];
$particularValue = someValue;
} else if ($precedenceArray[$someCode] <= $precedenceOfCodeCaptured) {
$particularValue = someValue;
}
};
$c();
break;
...
}
}//end of private method
Every time Foo is called, you create a new function/closure, since you evaluate a function(), and that's what evaluating function() does!
If you'd like to have Foo() return the same function/closure each time, only evaluate it once. Perhaps use a singleton pattern, where you'll check if some higher-scoped variable that holds the function has been initialized, and initialize it if not.
For example:
$c = null;
private function Foo(){
if ($c == null) {
$c = function() use ( $whatever){
static $x = 0;
echo "x= $x";
$x++;
...
};
}
$c();
}//end of private method
(but please don't use globals in your actual code!)
Try this:
static $x = 0;
private function Foo() {
$c = function() use ( $whatever){
echo "x= $x";
self::$x++;
...
};
$c();
}
<?php
class example{
private function foo(){
static $_closure;
if( ! $_closure ){
$_closure = function(){
static $_state;
/* . . . */
};
}
$_closure();
}
}
Note that the closure is static (it is created on first use, and not again), as is the variable that holds state inside the closure.
However, as stated in other answers, this is "pointless" at best. $_closure should be another class method; $_state should be a class property (there is no need for static anything in the closure, in foo(), nor in the class). It is not "cleaner" or more readable or performant (in fact, the opposite is likely true) to use a closure like this.
It might make sense if you were doing something like:
returning the closure for use elsewhere
dynamically creating the function at runtime (i.e., based on foo() args)
something else dynamic and interesting
…but as it stands, this is simply the wrong approach. The tools to do this already exist.

Get the number of time a class method has been invoked?

Let's say I have this class.
class foo{
function a(){
return $this;
}
}
And I instantiate it as:
$O = new foo();
$O->a()
->a()
->a();
Is there any way to know, in that last function ->a() how many times it was called before?
So, I could output like 'method ->a() has been called twice before this.'
I would like to find out this, without using increment values like declaring a property and then increment it increment it, everytime it is called in a function.
I am just hopping if there is a hidden feature in OOP that can provide for this solution
You can use a static variable inside the method:
class foo{
function a(){
// $count will be initialized the first time a() was called
static $count = 0;
// counter will be incremented each time the method gets called
$count ++;
echo __METHOD__ . " was called $count times\n";
return $this;
}
}
Note that static has a different meaning when used inside a method or function and it has nothing to do with static class members - although it is the same keyword. It means that the variable will be created and initialized only once when the method has been called for the first time.
However, in the example above there is no way to reinitialize that counter. If you want to do that you may introduce a parameter or something like this. Also you may not use a static variable but an object property.. There are tousand ways to do it, tell me your exact application needs I may give a more specific example....
In comments it was suggested to use a decorator for this job. I like this idea and will give a simple example:
class FooDecorator
{
protected $foo;
protected $numberOfCalls;
public function __construct($foo) {
$this->foo = $foo;
$this->reset();
}
public function a() {
$this->numberOfCalls++;
$this->foo->a();
return $this;
}
public function resetCounter() {
$this->numberOfCalls = 0;
}
public function getNumberOfCalls() {
return $this->numberOfCalls;
}
}
Usage example:
$foo = new FooDecorator(new foo());
$foo->a()
->a()
->a();
echo "a() was called " . $foo->getNumberOfCalls() . " times\n";

PHP object method doesn't behave as I expect

I can't quite understand why the output of this code is '1'.
My guess is that php is not behaving like most other OO languages that I'm used to, in that the arrays that php uses must not be objects. Changing the array that is returned by the class does not change the array within the class. How would I get the class to return an array which I can edit (and has the same address as the one within the class)?
<?php
class Test
{
public $arr;
public function __construct()
{
$this->arr = array();
}
public function addToArr($i)
{
$this->arr[] = $i;
}
public function getArr()
{
return $this->arr;
}
}
$t = new Test();
$data = 5;
$t->addToArr($data);
$tobj_arr = $t->getArr();
unset($tobj_arr[0]);
$tobj_arr_fresh = $t->getArr();
echo count($tobj_arr_fresh);
?>
EDIT: I expected the output to be 0
You have to return the array by reference. That way, php returns a reference to the array, in stead of a copy.
<?php
class Test
{
public $arr;
public function __construct()
{
$this->arr = array();
}
public function addToArr($i)
{
$this->arr[] = $i;
}
public function & getArr() //Returning by reference here
{
return $this->arr;
}
}
$t = new Test();
$data = 5;
$t->addToArr($data);
$tobj_arr = &$t->getArr(); //Reference binding here
unset($tobj_arr[0]);
$tobj_arr_fresh = $t->getArr();
echo count($tobj_arr_fresh);
?>
This returns 0.
From the returning references subpage:
Unlike parameter passing, here you have to use & in both places - to
indicate that you want to return by reference, not a copy, and to
indicate that reference binding, rather than usual assignment, should
be done
Note that although this gets the job done, question is if it is a good practice. By changing class members outside of the class itself, it can become very difficult to track the application.
Because array are passed by "copy on write" by default, getArr() should return by reference:
public function &getArr()
{
return $this->arr;
}
[snip]
$tobj_arr = &$t->getArr();
For arrays that are object, use ArrayObject. Extending ArrayObject is probably better in your case.
When you unset($tobj_arr[0]); you are passing the return value of the function call, and not the actual property of the object.
When you call the function again, you get a fresh copy of the object's property which has yet to be modified since you added 5 to it.
Since the property itself is public, try changing:
unset($tobj_arr[0]);
To: unset($t->arr[0]);
And see if that gives you the result you are looking for.
You are getting "1" because you are asking PHP how many elements are in the array by using count. Remove count and use print_r($tobj_arr_fresh)

`static` keyword inside function?

I was looking at the source for Drupal 7, and I found some things I hadn't seen before. I did some initial looking in the php manual, but it didn't explain these examples.
What does the keyword static do to a variable inside a function?
function module_load_all($bootstrap = FALSE) {
static $has_run = FALSE
It makes the function remember the value of the given variable ($has_run in your example) between multiple calls.
You could use this for different purposes, for example:
function doStuff() {
static $cache = null;
if ($cache === null) {
$cache = '%heavy database stuff or something%';
}
// code using $cache
}
In this example, the if would only be executed once. Even if multiple calls to doStuff would occur.
Seems like nobody mentioned so far, that static variables inside different instances of the same class remain their state. So be careful when writing OOP code.
Consider this:
class Foo
{
public function call()
{
static $test = 0;
$test++;
echo $test . PHP_EOL;
}
}
$a = new Foo();
$a->call(); // 1
$a->call(); // 2
$a->call(); // 3
$b = new Foo();
$b->call(); // 4
$b->call(); // 5
If you want a static variable to remember its state only for current class instance, you'd better stick to a class property, like this:
class Bar
{
private $test = 0;
public function call()
{
$this->test++;
echo $this->test . PHP_EOL;
}
}
$a = new Bar();
$a->call(); // 1
$a->call(); // 2
$a->call(); // 3
$b = new Bar();
$b->call(); // 1
$b->call(); // 2
Given the following example:
function a($s){
static $v = 10;
echo $v;
$v = $s;
}
First call of
a(20);
will output 10, then $v to be 20. The variable $v is not garbage collected after the function ends, as it is a static (non-dynamic) variable. The variable will stay within its scope until the script totally ends.
Therefore, the following call of
a(15);
will then output 20, and then set $v to be 15.
Static works the same way as it does in a class. The variable is shared across all instances of a function. In your particular example, once the function is run, $has_run is set to TRUE. All future runs of the function will have $has_run = TRUE. This is particularly useful in recursive functions (as an alternative to passing the count).
A static variable exists only in a
local function scope, but it does not
lose its value when program execution
leaves this scope.
See http://php.net/manual/en/language.variables.scope.php
To expand on the answer of Yang
If you extend a class with static variables, the individual extended classes will hold their "own" referenced static that's shared between instances.
<?php
class base {
function calc() {
static $foo = 0;
$foo++;
return $foo;
}
}
class one extends base {
function e() {
echo "one:".$this->calc().PHP_EOL;
}
}
class two extends base {
function p() {
echo "two:".$this->calc().PHP_EOL;
}
}
$x = new one();
$y = new two();
$x_repeat = new one();
$x->e();
$y->p();
$x->e();
$x_repeat->e();
$x->e();
$x_repeat->e();
$y->p();
outputs:
one:1
two:1
one:2
one:3 <-- x_repeat
one:4
one:5 <-- x_repeat
two:2
http://ideone.com/W4W5Qv
static variable in a function means that no matter how many times you call the function, there's only 1 variable.
<?php
class Foo{
protected static $test = 'Foo';
function yourstatic(){
static $test = 0;
$test++;
echo $test . "\n";
}
function bar(){
$test = 0;
$test++;
echo $test . "\n";
}
}
$f = new Foo();
$f->yourstatic(); // 1
$f->yourstatic(); // 2
$f->yourstatic(); // 3
$f->bar(); // 1
$f->bar(); // 1
$f->bar(); // 1
?>
Inside a function, static means that the variable will retain its value each time the function is called during the life of the page load.
Therefore in the example you've given, if you call a function twice, if it set $has_run to true, then the function would be able to know that it had previously been called because $has_run would still be equal to true when the function starts the second time.
The usage of the static keyword in this context is explained in the PHP manual here: http://php.net/manual/en/language.variables.scope.php

Reset Class Instance Variables via Method

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
?>

Categories