mercredi 30 septembre 2015

Accessing object properties in PHP

I am trying to access properties of a custom object in PHP:

<?php

namespace App\Classes;

use Illuminate\Database\Eloquent\Model;

class AED extends Model {

    protected $table = 'aeds';
    protected $fillable = ['owner', 'street', 'postal_code', 'locality', 'latitude', 'longitude', 'annotation_type'];
    public $timestamps = true;

    public $id;
    public $owner;
    public $object;
    public $street;
    public $postalCode;
    public $locality;
    public $latitude;
    public $longitude;
    public $annotation_type;
    public $distance;

    public function set($data) {
        foreach ($data as $key => $value) {
            if(property_exists($this, $key)) {
                $this->$key = $value;
            }
        }
    }
}

The code to access these properties:

<?php
namespace App\Transformer;

use App\Classes\AED;
use League\Fractal\TransformerAbstract;


class AEDTransformer extends TransformerAbstract {
    public function transform(AED $aed) {
        return [
            'data' => $aed->owner
        ];
    }
}

When I call the function, I get this as a response:

{
data: [
{
data: null
}
],
meta: "TestMeta"
}

The strange thing is, when I just var_dump the object I get the full info:

...
 protected 'original' => 
    array (size=11)
      'id' => int 1
      'owner' => string 'Owner 1' (length=7)
      'object' => string 'Object 1' (length=8)
      'street' => string 'Street 1' (length=8)
      'postal_code' => string '11111' (length=5)
      'locality' => string 'Locality 1' (length=10)
      'latitude' => float 100
      'longitude' => float 100
      'annotation_type' => string '1' (length=1)
      'created_at' => string '0000-00-00 00:00:00' (length=19)
      'updated_at' => string '0000-00-00 00:00:00' (length=19)
...

So the data can be taken from the database as expected and is being received as well. Why does the accessing not work then and I receive a "null".

I use the "set" method inside the custom function here:

class AEDHelper {
    static public function searchAED($position) {
        $var1 = $position['latitude'];
        $var2 = $position['longitude'];
        $var3 = $position['latitude'];

        $queryResults = DB::select(DB::raw("SQLCODE"));
        $results = [];

        foreach ($queryResults as $results) {
            $aed = new AED();
            $aed->set($results);
            $results[] = $aed;
        }

        return $results;

    }

Here I create a new AED() instance. So I would guess I need to define the object properties therefore as now not Eloquent will be used but a custom AED class needs to be instantiated for displaying SQL results.

Best



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire