Accessing "protected" part of object - php

I have the variable $customerData that stores an object. When I execute print_r($customerData) I get something similar to the below.
Balanced\Customer Object(
[_collection_uris:protected] => Array(
[reversals] => Array(
[class] => Balanced\Reversal
[uri] => /v1/customers/1234123412341234/reversals
)
)
[_member_uris:protected] => Array(
[source] => Array(
[class] => Balanced\Card
[uri] => /v1/customers/1234123412341234/cards/987698769876
)
)
[_type] => customer
[twitter] => twitterHandle
[phone] => 5551231234
)
I'm having issues accessing the uri inside _member_uris:protected.
print_r($customerData->_member_uris:protected); #Throws error "unexpected ':'"
print_r($customerData->_member_uris); #Throws error " Undefined property"
print_r($customerData['_member_uris']); #Throws error "Cannot use object of type array"
What is the process of accessing that part of the object?

Members declared protected can be accessed only within the class itself and by inherited and parent classes. You could add a method in your class to get it, using setAccessible(), like:
//function inside your class
public static function getProtectedProp($class, $propName) {
$reflClass = new ReflectionClass($class);
$property = $reflClass->getProperty($propertyName);
$property->setAccessible(true);
return $property->getValue($class);
}
and you can do:
getProtectedProp($someClassObject, 'protectedPropertyName');
Source:: Reading Protected Property

You can't access protected or private properties from global code or regular functions. From the documentationof Visibility:
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and parent classes.
Members declared as private may only be accessed by the class that defines the member.

Related

Relational Data Help Silverstripe

Im trying to extend https://github.com/Quadra-Digital/silverstripe-schema to be able to better handle nested schemas. I've managed to get it working all though it breaks one of the very useful features Dynamic Values.
It currently uses a DataObject called RelatedObject to map its related object which works fine when there is only one level of nesting. However once you get further into it and have SchemaInstances nested upon SchemaPropertys you lose the overarching owner, and the RelatedObject becomes the Property that the Instance is nested under.
class SchemaInstance extends DataObject {
private static $db = [
'ParentClass' => 'Varchar(255)'
];
private static $has_one = [
'RelatedObject' => 'DataObject',
'Schema' => 'Schema',
];
private static $has_many = [
'Properties' => 'SchemaProperty'
];
class SchemaProperty extends DataObject {
private static $db = [
'Title' => 'Varchar(255)',
'ValueStatic' => 'Varchar(255)',
'ValueDynamic' => 'Varchar(255)'
];
private static $has_one = [
'ParentSchema' => 'SchemaInstance'
];
private static $has_many = [
'NestedSchemas' => 'SchemaInstance'
];
This is what is currently saved when I created the nested schema instance.
52 SchemaInstance 2018-03-04 04:28:38 2018-03-04 04:28:38 0 File 8 0 96 SchemaProperty
I need it to look like this
52 SchemaInstance 2018-03-04 04:28:38 2018-03-04 04:28:38 0 File 8 0 96 *ActualParentClass*
I have tried getting the owner in the SchemaObjectExtension (Which works fine, I just can't figure out how to use that rather than the default)
class SchemaObjectExtension extends DataExtension {
private static $has_many = [
'SchemaInstances' => 'SchemaInstance.RelatedObject',
];
I'd be happy with just being able to save the owner class to the db somehow and the reference that. I've tried getting it from the DataObject but it gives a
"getOwner() is not a method on Dataobject" error.
Thanks for any help

PHP Array Object to Serialize

I am trying to convert a PHP array object to an JSON.Following is the PHP Array Object;
Array
(
[0] => Project\Man\Model\Branch Object
(
[id:protected] => 123456
[name:protected] => Parent Branch
[type:protected] => services
)
)
I tried Serializing it but its not in a friendly readable object.
I tried the following:
json_encode
serialize
a:1:{i:0;O:23:"Project\Man\Model\Branch ":3:{s:5:"*id";s:36:"123456";s:7:"*name";s:20:"Parent Branch";s:7:"*type";s:8:"services";}}[{}]
I am trying for some solution where i can get JSON. any help.
If you just want json, you should only use json_encode(), not serialize().
Since your object properties are set as protected, they will however not be available when you encode the object whitout some additional help.
This is where the interface JsonSerializable comes into play.
You need to make sure that the object you want to encode implements the interface. Then you need to add a jsonSerialize() method to the class.
class Branch implements \JsonSerializable
{
protected $id;
protected $name;
protected $type;
// ... your class code
public function jsonSerialize()
{
// Return what you want to be encoded
return [
'id' => $this->id,
'name' => $this->name,
'type' => $this->type,
];
}
}
If you now pass this object through json_encode() and you'll get a json string with what our new method returns.

Can a property of an Abstract Class be access outside the class?

Is is possible to access a variable in a PHP abstract class, i.e.
abstract class Settings
{
public $application = array
(
'Name' => 'MyApp',
'Version' => '1.0.0',
'Date' => 'June 1, 2017'
)
}
echo Settings::application ['Name']; // doesn't work
You could make the variable static, as long as it doesn't need to allow differentiation across instances (i.e. instance variable):
<?php
// example code
abstract class Settings
{
public static $application = array
(
'Name' => 'MyApp',
'Version' => '1.0.0',
'Date' => 'June 1, 2017'
);
}
echo Settings::$application ['Name'];
Run it in this playground example.
Though your original access of application was similar to that of a constant. use const to declare a Class constant:
abstract class Settings
{
const application = array
(
'Name' => 'MyApp',
'Version' => '1.0.0',
'Date' => 'June 1, 2017'
);
}
echo Settings::application ['Name'];
Run it in this playground example.
Abstract Classes can not be directly instantiated as they rely on
child classes to fully implement the functionality.
So if you want to check your variable I would make new class and inherit from your Settings class. You will have to use it with inheritance anyway.
class MySettings extends Settings
{
....
}
$mySettings = new MySettings();
echo $mySettings->application['Name'];
More about abstract classes http://culttt.com/2014/03/26/abstract-classes/

How to get the property of Object in Symfony

Hey How Can i get any specific property from the whole object.
I have this query
$portfolios = $this->getDoctrine()
->getRepository('MunichInnovationGroupBundle:PmPortfolios')
->findBy(array('user' => '1'));
foreach ($portfolios as $portfolio){
if($portfolio.isDefault == true){
$default_portfolio = $portfolio;
}
echo $portfolio.name;
}
The complete object looks like this
MunichInnovationGroup\Bundle\Entity\PmPortfolios Object
(
[id:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => 991654b4-aa73-11e1-bdce-4a7b883b8e17
[portfolioName:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Umair Portfolio 1
[description:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Thsi is the description for Umairs portfolio 1
[permalink:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => premalink
[sharingCode:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => asdbnvg123dg
[shared:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] =>
[sharedPortfolioCalls:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] =>
[isDefault:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => 1
[user:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Proxies\MunichInnovationGroupBundleEntityUmUsersProxy Object
How can I get the isDefault value ?
Thanks in advance
If you have your entity set up correctly with all generated set/get methods, and isDefault is a private property (as it seems so from the var_dump) you can simply use
if($portfolio->getIsDefault())
For better method naming I would write a method in the entity:
public function isDefault() {
return $this->isDefault;
}
and then use
if($portfolio->isDefault())

How can I reach an element in an Object?

I'm trying to reach an element in an object array. But I couldn't succeed.
Let's think this as an object called $result
How can I reach maskedNumber?
Braintree_Result_Successful Object
(
[success] => 1
[_returnObjectName:private] => customer
[customer] => Braintree_Customer Object
(
[_attributes:protected] => Array
(
[creditCards] => Array
(
[0] => Braintree_CreditCard Object
(
[_attributes] => Array
(
[maskedNumber] => ***********5897
Since the _attributes property of Braintree_Customer is protected you will need to define an accessor method. The other _attributes property of Braintree_CreditCard also looks like it's supposed to be protected, so I've assumed an identical accessor should exist:
$cards = $object->customer->getAttribute('creditCards');
$number = $cards[0]->getAttribute('maskedNumber');
Accessor method to be placed in both classes:
function getAttribute($attribute) {
return $this->_attributes[$attribute];
}
Edit:
Just to improve upon my original answer a little, I would put some decent error checking in an actual accessor method.
function getAttribute($attribute) {
if (isset($this->_attributes[$attribute])) {
return $this->_attributes[$attribute];
}
return NULL;
}
You could also consider using the magic methods __get() and __set() to act as getters and setters.
I solved the problem by asking braintreepayments. They said that I could retrieve this data after I add user to braintree. But my solution is if I really needed this at the very beginning would be to take it with REGEX. For people who are looking for a great online payment company I suggest you to go with braintree
I know this is old, but this might help some.
Braintree has methods for returning the protected information that's returned from functions like Braintree_Customer::create();
$result = Braintree_Customer::create(array(
'firstName' => $_POST['first_name'],
'lastName' => $_POST['last_name'],
'email' => $_POST['email'],
'creditCard' => array(
'cardholderName' => $_POST['cardholder_name'],
'number' => $_POST['number'],
'expirationMonth' => $_POST['month'],
'expirationYear' => $_POST['year'],
'cvv' => $_POST['cvv'],
'billingAddress' => array(
'postalCode' => $_POST['postal_code']
)
)
));
var_dump($result->customer->__get('id'));
var_dump($result->customer->__get('creditCards'));
The _attributes of customer are protected, but the get function returns them.
This method does not require re-requesting data from Braintree.
try
$Result->customer->_attributes['creditCards'][0]->_attributes['maskedNumber']
with $result->customer you should get the *Braintree_Customer* Object and then in that object you should have methods to retrieve the cards as those methods are protected and cannot be accessed directly. Something like
$customer = $result->customer;
foreach($customer->getCreditCards() as $card)
{
echo $card->getMaskedNumber(); // You will need to create that method too
}
Example of getCreditCards method:
Class Braintree_Customer
{
protected $creditCards;
function getCreditCards()
{
return $creditCards;
}
...
}

Categories