在PHP中访问对象属性

时间:2015-09-30 17:37:03

标签: php laravel-5

我试图在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;
            }
        }
    }
}

访问这些属性的代码:

<?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
        ];
    }
}

当我调用该函数时,我将此作为回复:

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

奇怪的是,当我只是var_dump对象时,我得到了完整的信息:

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

因此,数据可以按预期从数据库中获取并且也正在接收。为什么访问不起作用,我收到“null”。

我在自定义函数中使用“set”方法:

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;

    }

这里我创建了一个新的AED()实例。因此我猜我需要定义对象属性,因为现在不会使用Eloquent,但需要实例化自定义AED类以显示SQL结果。

最佳

1 个答案:

答案 0 :(得分:0)

您不必在模型中定义字段。 Eloquent使它们动态可用。

如果你想填写那些字段,你可以在模型中没有它们。因为如果您尝试为其设置值,该字段将可用。

这是如何

$aed = new AED;
$aed->owner =  "The Owner";
$aed->object = "The Object";
....
....
....

$aed->save();

或者这也可以使用

AED::create([
  'owner' => "The Owner",
  'object' => "The Object",
  .....
  .....
  .....
]);

或者如果您想要更新现有模型。

$aed = AED::find(1);
// change owner
$aed->owner= "New Owner";

$aed->save();