开发者

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

开发者 https://www.devze.com 2023-03-20 18:47 出处:网络
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\'

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!


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


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

Note: will export only public and set variables


<?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;
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消