Alex Waters
Alex Waters

Reputation: 4360

How do I convert values stored in an object to an array

Here is my code:

   class Sub extends DatabaseObject {

  protected static $table_name="subs";
  protected static $db_fields=array('id', 'product_id', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8', 'col9', 'col10', 'col11', 'col12');

  public $id;
  public $product_id;
  public $col1;
  public $col2;
  public $col3;
  public $col4;
  public $col5;
  public $col6;
  public $col7;
  public $col8;
  public $col9;
  public $col10;
  public $col11;
  public $col12;

My find_subs_on($product_id) function calls another function that passes values into the public variables above.

My problem is that I want to display the values above in a table, with each col inside a <td>

Do I create a function inside the class that takes those values and returns an array, and then i foreach the array?

Do I create an array in the view, and pass in $sub->col1, $sub->col2 etc.?

I would love if someone could point to an example of the correct way to do this. Thank you very much for any help!

Upvotes: 1

Views: 58

Answers (3)

Glass Robot
Glass Robot

Reputation: 2448

You can use foreach on an object but if you want to you can typecast an object to an array:

 $obj = new ClassName;
 $obj_to_array = (array) $obj;
 print_r($obj_to_array);

Upvotes: 2

MeLight
MeLight

Reputation: 5555

This is probably what you need: get_object_vars($object)

Note: will export only public and set variables

Upvotes: 1

genesis
genesis

Reputation: 50966

<?php
  class test
  {
      function get_variable($var)
      {
          return $this->$var;
      }

      function set_variable($var, $value)
      {
          private $this->$var = $value
      }
  }

  $test = new test;
  $test->set_variable("foo", "bar");
  $variable = $test->get_variable("foo");
?>

or easier, but bad

<?php
  class test
  {
  }

  $test = new test;
  $test->foo = bar;
  $variable = $test->foo;
?>

Upvotes: 1

Related Questions