Mostafa Abedi
Mostafa Abedi

Reputation: 541

how can i access properties defined dynamically inside php class

trying to develop a class associated with table(like in frameworks). assume we have a class named Book

class Book
{  
  public function save()
  {
     ....
  }

 }

$book = new book;
$book->id = '1';
$book->name = 'some';
$book->save();

the problem is how can i access this dynamically created properties inside save() to save new record

Upvotes: 1

Views: 44

Answers (3)

Dmitriy Buteiko
Dmitriy Buteiko

Reputation: 644

here is complete code that you should use:

<?php 

class Book
{  
  public function save()
  {
     $vars = get_object_vars($this);
     var_dump($vars);
  }

 }

$book = new book;
$book->id = '1';
$book->name = 'some';
$book->save();

?>

Upvotes: 1

KIKO Software
KIKO Software

Reputation: 16688

You can find properties in an object with:

$properties = get_object_vars($book);

See: http://php.net/manual/en/function.get-object-vars.php

Upvotes: 2

Calimero
Calimero

Reputation: 4288

You could do it that way (note that there are other solutions to this problem) :

public function save() {
    $properties = get_object_vars($this);
    print_r($properties);
    // do something with it.
}

Upvotes: 2

Related Questions