Search code examples
phpclassprivate

Adding a defined variable to a private class in PHP


Why can't I carry a variable ($last_id) into a class?

//get value of last sql row
$last_id = $conn->lastInsertId():
//create class
Class CropAvatar {
  private $id = $last_id;
  private $src;
  private $dstDir = '../some path';
}

private $src and private dstDir works fine.

How can I carry a variable's value into a class?


Solution

  • You could get that value within class like you want. You could achieve your goal by using constructor like below:

    Class CropAvatar {
    
      private $id;
      private $src;
      private $dstDir = '../some path';
    
      public function __construct($last_id) {
        $this->id = $last_id;
      }
    
    }