Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

php - Get string within protected object

I am trying to get the the string "this info" inside this object lets call it $object, but data is protected, how can I access that pocket?

    object(something)#29 (1) {
  ["_data":protected]=>
  array(10) {
    ["Id"]=>
    array(1) {
      [0]=>
      string(8) "this info"
    }
    ["SyncToken"]=>
    array(1) {
      [0]=>
      string(1) "0"
    }
    ["MetaData"]=>
    array(1) {

Obviously $object->_data gives me an errorCannot access protected property

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are a few alternative ways to get a private/protected properties of an object that doesn't require you to modify the original source code.

Option 1 - Reflection:

Wikipedia defines Reflection as

... the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of the program at runtime. [Reflection (computer_programming)]

In this case you may want to use reflection to examine the properties of the object and set as accessible the protected property _data

I do not recommend reflection unless you have very specific use cases where it may be required. This is an example on how to get your private/protected parameter using Reflection with PHP:

$reflector = new ReflectionClass($object);
$classProperty = $reflector->getProperty('_data');
$classProperty->setAccessible(true);
$data = $classProperty->getValue($object);

Option 2 - Subclasses (protected properties only):

If the class is not final, you can create a subclass of the original. This will give you access to the protected properties. In the subclass you could write your own getter methods:

class BaseClass
{
    protected $_data;
    // ...
}

class Subclass extends BaseClass
{
    public function getData()
    {
        return $this->_data
    }
}

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...