Reputation: 199
Is it possible to do object++ in php?
I'am just wondering if something like this is possible, if so how would I achive something like this?
Example:
class x
{
private $data = 0;
}
$a = new x();
$a++;
Upvotes: 3
Views: 99
Reputation: 34673
You can not overwrite ++ and -- (nor any other) operator in PHP, unlike C++ or Ruby for example, if that is the question.
Upvotes: 2
Reputation: 68476
You cannot access the private
members from outside of the class , However you can increment a public
variable outside of your class.
<?php
class x
{
private $data = 0;
public $newdata = 0;
}
$a = new x();
$a->newdata++;
var_dump($a);
OUTPUT :
object(x)[1]
private 'data' => int 0
public 'newdata' => int 1
Using Reflections you can even modify the private properties outside , but this breaks the OOP paradigm , so don't do it. This is just for your understanding..
<?php
class x
{
public $newdata = 0;
private $data = 0;
}
$a = new x();
var_dump($a);
# Incrementing public var
$a->newdata++;
# Setting the private var
$b = new ReflectionProperty(get_class($a), 'data');
$b->setAccessible(true);
$b->setValue($a, $b->getValue($a)+1);
var_dump($a);
OUTPUT :
class x#1 (2) {
private $data =>
int(0)
public $newdata =>
int(0)
}
class x#1 (2) {
private $data =>
int(1)
public $newdata =>
int(1)
}
Upvotes: 2
Reputation: 1857
I assume you are trying to increase the variable $data inside the class x?
If so, you will want to do something like this:
class x
{
private $data = 0;
public function increaseData()
{
$this->data++;
}
}
$a = new x();
$a->increaseData();
Upvotes: 4