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".

Best



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1O2qx9g
via IFTTT

Aucun commentaire:

Enregistrer un commentaire