How to access the values of a private object in PHP?

Asked

Viewed 44 times

-2

I have the following variable:

var_dump($bankAccount);

Printing:

Object(Pagarme Sdk Bankaccount Bankaccount)#35 (11) {
["id":"Pagarme Sdk Bankaccount Bankaccount":private]=>
int(17929453)
["bankCode":"Pagarme Sdk Bankaccount Bankaccount":private]=>
string(3) "104"
["agency":"Pagarme Sdk Bankaccount Bankaccount":private]=>
string(4) "0000"
["agenciaDv":"Pagarme Sdk Bankaccount Bankaccount":private]=>
NULL ["account":"Pagarme Sdk Bankaccount Bankaccount":private]=>
string(5) "12345"
["contaDv":"Pagarme Sdk Bankaccount Bankaccount":private]=>
string(1) "5"
["documentNumber":"Pagarme Sdk Bankaccount Bankaccount":private]=> string(11) "04900000000"
["documentType":"Pagarme Sdk Bankaccount Bankaccount":private]=>
string(3) "Cpf"
["legalName":"Pagarme Sdk Bankaccount Bankaccount":private]=>
string(12) "Maykel Esser"
["dateCreated":"Pagarme Sdk Bankaccount Bankaccount":private]=>
Object(Datetime)#37 (3) { ["date"]=> string(26) "2019-01-02 20:03:14.031000" ["timezone_type"]=> int(2) ["Timezone"]=> string(1) "Z" } ["type":"Pagarme Sdk Bankaccount Bankaccount":private]=>
string(14) "current count" }

That is, the return of the $bankAccount var_dump is an object. I need the ID that is inside this object, and save it in a variable for later use.

I tried to pull this way:

$idBanco = $bankAccount->id;

But I got the mistake:

Fatal error: Uncaught Error: Cannot access private Property Pagarme Sdk Bankaccount Bankaccount::$id

How to proceed?

  • If it is private, external access is not allowed. Read the class documentation and see if there is a method for doing so.

1 answer

1


If the object property is private, it is not possible to access it directly, add a method to the class that returns that id:

class Exemplo {
     // ...

     public function getId() {
          return $this->id;
     }
 }

If not possible, you can create another class that will extend the first one and use it in its place

class MeuExemplo extends Exemplo {
     public function getId() {
          return $this->id;
      }
 }

But it is necessary that the property id be the type protected

  • 1

    If the field is private it will not be inherited in the child classes; only protected and public are inherited.

  • @Andersoncarloswoss thanks for the reminder

  • Perfect! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.