views:

31

answers:

4

excecute() method always return an "informational" object after use current() method i get an array always.

How can i obtain an object (with objects) to iterate like this, (no ORM):

foreach($obj as $o)
{
   echo $o->name;
   echo $o->email;
}

Instead of using current, next, etc.

A: 

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

Source: http://www.php.net/manual/en/language.oop5.iterations.php

class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach($class as $key => $value) {
    print "$key => $value\n";
}
echo "\n";


$class->iterateVisible();

Result:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var
Sarfraz
A: 

I really like the standalone Doctrine ArrayCollection class:

Code: http://trac.doctrine-project.org/browser/trunk/lib/Doctrine/Common/Collections/ArrayCollection.php?rev=7481

API: http://www.doctrine-project.org/api/common/2.0/doctrine/common/collections/arraycollection.html


$objects = new Doctrine\Common\Collections\ArrayCollection();
$objects[] = new MyClass('name 1', 'email 1');
$objects[] = new MyClass('name 1', 'email 1');

foreach ($objects as $o)
{
    echo $o->name;
    echo $o->email;
}
gimpe
A: 

Using Kohana3 DB you would do something like this:

$query = DB::select("*")->from("table")->where("key", "=", 20)->execute();
foreach ($query->as_array() as $row) {
    echo $row->key;
    echo $row->name;
    echo $row->email;
}
sberry2A
A: 

As I say Execute() return an Array, and using current() you get the resulset as an array of arrays, reading kohana V3 API, found this:

$users = DB::select()->from('users')->where('salesman', '=', TRUE) ->as_object()->execute();

foreach ($users as $user) { echo $user->email; }

Oliver