为什么我只能访问此PHP对象中的第一个受保护属性?

时间:2014-10-02 16:15:53

标签: php

这有效:

public function import_tickets($user = null) {
    $tickets = kyTicket::getAll(
        kyDepartment::getAll(),
        kyTicketStatus::getAll(),
        array(),
        kyUser::getAll()
    );
    $reflect = new ReflectionClass($tickets);
    $ts = $reflect->getProperty('objects');
    $ts->setAccessible(true);
    $content = $ts->getValue($tickets);
    $output = '';
    foreach ( $content as $c ) {
        $output .= $c->id . "\n";
    }
    print_r($output);
}

输出:

[root@matthewharris External]# php test.php 

1
2
3
4
5
6

我正在尝试从以下对象访问display_id

[4] => kyTicket Object
    (
        [id:protected] => 5
        [flag_type:protected] => 0
        [display_id:protected] => RXH-123-45678
        [department_id:protected] => 5
        [status_id:protected] => 3
        [priority_id:protected] => 1

但是当我这样做时,我收到以下错误:

[02-Oct-2014 12:14:29] PHP   3. kyObjectBase->__get($api_field_name = 'display_id') /var/www/html/site/public_html/inc/QA/External/test.php:43
[02-Oct-2014 12:14:29] PHP   4. trigger_error('Undefined property: kyTicket::$display_id', 1024) /var/www/html/site/public_html/inc/QA/External/api-kayako/kyObjectBase.php:573
[02-Oct-2014 12:14:29] PHP Notice:  Undefined property: kyTicket::$display_id in /var/www/html/site/public_html/inc/QA/External/api-kayako/kyObjectBase.php on line 573

为什么我可以毫无问题地访问id,但不会捕获display_id

1 个答案:

答案 0 :(得分:0)

$reflect = new ReflectionClass($tickets); 
$reflectionProperty = $reflect->getProperty('objects');
$reflectionProperty->setAccessible(true); 
$objects = $reflectionProperty->getValue($tickets);

// you need object "tickets" - property "objects" for the iteration

foreach($objects as $object) {
   listProperties($object);
}

function listProperties($object)
{
    echo 'Properties for Object: ' . get_class($object);

    $reflect = new ReflectionClass($object); 

    $properties = $reflect->getProperties(
        ReflectionProperty::IS_PUBLIC + 
        ReflectionProperty::IS_PROTECTED
    );

    foreach ($properties as $prop) {
        echo $prop->getName() . "\n";
    }
}