0

I want to set my value in object using public method. But I can't find to make it work

<?php
        class User{
            public $id;

            public function ToSynchData(){
                $this->$id = "1";
            }
        }
        $new = new User;
        $new->ToSynchData();
        $new->$id;
    ?>
Robin Carlo Catacutan
  • 13,249
  • 11
  • 52
  • 85

3 Answers3

2
public $id;

public function ToSynchData(){
    $this->id = 1;
}

$new = new User;
$new->ToSynchData();
echo $new->id; // 1

EDIT: Why static all of a sudden?

Sherlock
  • 7,525
  • 6
  • 38
  • 79
2
class User{
    public $id;
    public function ToSynchData(){
        $this->id = "1";
    }
}

$new = new User();
$new->ToSynchData();
print_r($new->id);
Ozerich
  • 2,000
  • 1
  • 18
  • 25
1

you are trying to access static property with -> whereas it is clearly written here

Static properties cannot be accessed through the object using the arrow operator ->.

therefore to access it you have to change it from static public to public

xkeshav
  • 53,360
  • 44
  • 177
  • 245