Question

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++;
Was it helpful?

Solution 2

You can not overwrite ++ and -- (nor any other) operator in PHP, unlike C++ or Ruby for example, if that is the question.

OTHER TIPS

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();

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

An ugly hack using Reflections... (Modifying private variables outside)

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)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top