Cannot access protected property PHP - php

trying to get values from object array, here is error and what i tried so far.
echo "<pre>";print_r($response->_value());//Call to undefined method OmiseCharge::_value()
echo "<pre>";print_r($response->_value); //Cannot access protected property PHP
actual array :
OmiseCharge Object
(
[OMISE_CONNECTTIMEOUT:OmiseApiResource:private] => 30
[OMISE_TIMEOUT:OmiseApiResource:private] => 60
[_values:protected] => Array
(
[object] => list
[from] => 2012-08-01T00:00:00+00:00
[to] => 2016-10-20T00:00:00+00:00
[offset] => 0
[limit] => 20
[total] => 201
[order] => chronological
[location] => /charges
[data] => Array
(
[0] => Array
(
[object] => charge
[id] => chrg_test_##############
[livemode] =>

echo "<pre>";print_r($response->offsetGet('data'));
worked thanks.

to access protected member of a call you need to implement getter method in class which are type of public.

Related

get the value of object inside the array in php

i am trying to get the merchantAccountId value from given below array
Array
(
[status] => 1
[result] => __PHP_Incomplete_Class Object
(
[__PHP_Incomplete_Class_Name] => Braintree_Result_Successful
[success] => 1
[_returnObjectName:Braintree_Result_Successful:private] => transaction
[transaction] => __PHP_Incomplete_Class Object
(
[__PHP_Incomplete_Class_Name] => Braintree_Transaction
[_attributes] => Array
(
[id] => 6vk28p
[status] => submitted_for_settlement
[type] => sale
[currencyIsoCode] => USD
[amount] => 800.00
[merchantAccountId] => contentorganisation
[orderId] =>
[createdAt] => DateTime Object
(
[date] => 2015-07-24 11:51:42
[timezone_type] => 3
[timezone] => UTC
)
)
)
)
)
my code is $result['result']['transaction'] .
when i print this i got this error
Fatal error: Cannot use object of type __PHP_Incomplete_Class as array in.
The result is OBJECT not array, so you have to call it by:
Array['result']->transaction->_attributes['id']
I work at Braintree. You should be able to access the merchant account ID by calling $result->transaction->merchantAccountId, (see Braintree docs).

How to get the values from the following array?

I got the following array as a result of an output from a web service? I printed the values in the array using the print_r() method as stated in the following description.
ARRAY OUTPUT:
Array
( [0] => stdClass Object
( [return] => stdClass Object
( [data] => stdClass Object
(
[status] => 50000
[adminUser] => 1
[atdUserid] => 58
[category] => [client] => [cur_designation] => TL
[currentEmpId] => E058
[digitPrefix] => 8,5,1,3,7,0
[email] => jaliya#codegen.net
[employeeId] => 58
[employee_status] => 1
[firstName] => Jaliya
[lastName] => Seneviratna
[last_login_date] => stdClass Object ( [date] => 6 [month] => 2 [year] => 2015 )
[letterPrefix] => D,C,U,T,Z,E
[loginName] => jaliya
[resourceStatus] =>
[taskPassword] => d6188c72995d80e1a8e00d34987e0f6b
[userId] => 118 )
[reason] => Success
[refetch] => 1
[status] => 1
) ) )
I got the above array by calling a webservice in php. I want to get the details out of this array. And the problem was that I couldn't get the stdClass objects casted into the right type. I tried the following code but it is not working. Can anyone help me to get the values inside the data[] out in php. I used the following code and it is not working and giving an exception.
CODE USED:
print_r(array_values($quote));
echo $quote[0]->data;
The exception was the following...
EXCEPTION RECIEVED:
Notice: Undefined property: stdClass::$data in C:\xampp\htdocs\WebServiceDemo-php\democlient.php on line 27
How to get values out from this array?
Please help me...
convert the object in to array using this function
get_object_vars(array);
USE Can Print each key value of data array like this:-
echo $quote[0]->data->status;
I will Print
50000

How can I loop through a stdObject's array without raising PHP notices/warnings?

I have the following stdObject obtained thru cURL / json_decode():
stdClass Object
(
[response] => stdClass Object
(
[status] => OK
[num_elements] => 1030
[start_element] => 0
[results] => stdClass Object
(
[publisher] => stdClass Object
(
[num_elements] => 1030
[results] => Array
(
[0] => stdClass Object
(
[id] => 1234
[weight] => 4444
[name] => Pub 1
[member_id] => 1
[state] => active
[code] =>
)
[1] => stdClass Object
(
[id] => 1235
[weight] => 4444
[name] => Pub 2
[member_id] => 2
[state] => active
[code] =>
)
)
)
)
[dbg_info] => stdClass Object
(
[instance] => instance1.server.com
[slave_hit] => 1
[db] => db1.server.com
[reads] => 3
[read_limit] => 100
[read_limit_seconds] => 60
[writes] => 0
[write_limit] => 60
[write_limit_seconds] => 60
[awesomesauce_cache_used] =>
[count_cache_used] =>
[warnings] => Array
(
)
[time] => 70.440053939819
[start_microtime] => 1380833763.4083
[version] => 1.14
[slave_lag] => 0
[member_last_modified_age] => 2083072
)
)
)
I'm looping through it in order to obtain each result's ID:
foreach ($result->response->results->publisher->results as $object) {
$publishers .= $object->id.",";
}
And although the code is working fine, PHP is rising the following notices/warnings:
PHP Notice: Trying to get property of non-object in /var/www/vhosts/domain.net/script.php on line 1
PHP Notice: Trying to get property of non-object in /var/www/vhosts/domain.net/script.php on line 1
PHP Warning: Invalid argument supplied for foreach() in /var/www/vhosts/domain.net/script.php on line 1
Any ideas? Thanks in advance!
Is it possible you have set the second parameter $assoc in json_decode() to true? Like this:
$result = json_decode($json_from_curl, true);
Thereby, getting back $result with all stdClass Objects converted to associative array.
EDIT:
If the $result you are getting is indeed an associative array, then we should treat it as such. Try replacing your foreach with this:
foreach ($result['response']['results']['publisher']['results'] as $arr) {
$publishers .= $arr['id'] . ",";
}
EDIT2:
From my own testing based on your code, everything should be working correctly. The notices/warnings should not occur. Perhaps some other code not shown in your question is causing it.

PHP analyzing, handling and converting some object to a stdClass

In our backoffice we have a core-system that generates models from the DB. When returning one object we make an instance of stdClass. All the columns from the query-result are set as proprties and when finished processing the query-result the stdClass-object is converted into a (we call it) Decorator-class. Basically the Decorator-class has one proprty $_oObject where the stdClass is stored into. We do this gain control over dynamically created objects. This works all fine.
However, I'm working on a webserver using SOAP. The webservice returns the whole Decorator-object (could possibly have sub-objects, also being Decorator objects, and sub-sub object.. and so on). This structure works perfectly fine with our internal system because we have control over the Decorator-object but for the outside world I want to revert the Decorator-object-structure into a stdClass instance with sub-classes also being stdClasses. Basically I want to remove all the 'nodes' in the print_r-result containing Decorator.
Any ideas how to achieve what I want (see results below). PHP's get_object_vars doesn't return anything and actually I'm stuck..
My sample data:
Decorator Object
(
[oClass:Decorator:private] => stdClass Object
(
[Id] => 1
[FAQCategoryId] => 1
[TitleId] => 1
[ContentId] => 2
[Views] => 226
[DateCreated] => 2011-10-31 11:17:44
[DateModified] =>
[Title] => My title..
[Content] => My content..
[AttachmentSet] => Array
(
[0] => Decorator Object
(
[oClass:Decorator:private] => stdClass Object
(
[Id] => 1
[LanguageId] => 1
[FAQItemId] => 1
[Attachment] => file1.pdf
)
)
[1] => Decorator Object
(
[oClass:Decorator:private] => stdClass Object
(
[Id] => 2
[LanguageId] => 1
[FAQItemId] => 1
[Attachment] => file2.pdf
)
)
)
)
)
I want to convert it into:
stdClass Object
(
[Id] => 1
[FAQCategoryId] => 1
[TitleId] => 1
[ContentId] => 2
[Views] => 226
[DateCreated] => 2011-10-31 11:17:44
[DateModified] =>
[Title] => My title..
[Content] => My content..
[AttachmentSet] => Array
(
[0] => stdClass Object
(
[Id] => 1
[LanguageId] => 1
[FAQItemId] => 1
[Attachment] => file1.pdf
)
[1] => stdClass Object
(
[Id] => 2
[LanguageId] => 1
[FAQItemId] => 1
[Attachment] => file2.pdf
)
)
)
I've figured it out. In my case I've created a function that returns the stdObject of a Decoarator object. In my Controller_Core-class I've made function that recursively handles a given object and returns the whole structure as one stdClass.
My code, if it is helpful to someone:
/**
* Controller_Core::RevertToStdClass
*
* #params: Decorator $oObject
* #return: stdClass $oObject
**/
public function RevertToStdClass(Decorator $oObject)
{
if(is_a($oObject, "Decorator"))
{
$oObject = $oObject->ReturnStdObject();
}
$aProperties = get_object_vars($oObject);
foreach($aProperties as $sProperty => $mValue)
{
if(is_array($mValue))
{
foreach($mValue as $mIndex => $mSubValue)
{
if(is_a($mSubValue, "Decorator"))
{
$oObject->{$sProperty}[$mIndex] = $this->RevertToStdClass($mSubValue);
}
}
}
else
{
if(is_a($mValue, "Decorator"))
{
$oObject->{$sProperty} = $this->RevertToStdClass($oObject->{$sProperty});
}
}
}
return $oObject;
}

php access object values

EDIT: Thanks everyone. I didn't even notice it was private lol, so I changed them from private to public, now it should be accessible... question now is how can I access the value of say 'backpackPosition'? thanks again!
TF2Inventory Object
(
[fetchDate] => 123456123
[items] => Array
(
[60] => TF2Item Object
(
[equipped] => Array
(
[scout] => 1
[sniper] => 1
[soldier] => 1
[demoman] => 1
[medic] => 1
[heavy] => 1
[pyro] => 1
[spy] => 1
)
[attributes] => Array
(
[0] => stdClass Object
(
[name] => custom employee number
[class] => set_employee_number
[value] => 0
)
[1] => stdClass Object
(
[name] => cannot trade
[class] => cannot_trade
[value] => 1
)
)
[backpackPosition] => 61
[className] => tf_wearable
[count] => 1
[defindex] => 170
[id] => 535518002
[level] => 20
[name] => Primeval Warrior
[quality] => unique
[slot] => misc
[tradeable] =>
[type] => Badge
)
[43] => TF2Item Object
(
[equipped] => Array
(
[scout] => 0
[sniper] => 0
[soldier] => 0
[demoman] => 0
[medic] => 0
[heavy] => 0
[pyro] => 0
[spy] => 0
)
[attributes] => Array
(
[0] => stdClass Object
(
[name] => cannot trade
[class] => cannot_trade
[value] => 1
)
)
[backpackPosition] => 44
[className] => tf_wearable
[count] => 1
[defindex] => 471
[id] => 535518003
[level] => 50
[name] => Proof of Purchase
[quality] => unique
[slot] => head
[tradeable] =>
[type] => Hat
)
[42] => TF2Item Object
(
[equipped] => Array
(
[scout] => 1
[sniper] => 1
[soldier] => 1
[demoman] => 1
[medic] => 1
[heavy] => 1
[pyro] => 1
[spy] => 1
)
[attributes] =>
[backpackPosition] => 43
[className] => tf_wearable
[count] => 1
[defindex] => 278
[id] => 541628464
[level] => 31
[name] => Horseless Headless Horsemann's Head
[quality] => unique
[slot] => head
[tradeable] =>
[type] => Hat
)
[59] => TF2Item Object
(
[equipped] => Array
(
[scout] => 0
[sniper] => 0
[soldier] => 0
[demoman] => 0
[medic] => 0
[heavy] => 0
[pyro] => 0
[spy] => 0
)
[attributes] => Array
(
[0] => stdClass Object
(
[name] => cannot trade
[class] => cannot_trade
[value] => 1
)
)
[backpackPosition] => 60
[className] => tf_wearable
[count] => 1
[defindex] => 115
[id] => 548155039
[level] => 10
[name] => Mildly Disturbing Halloween Mask
[quality] => unique
[slot] => head
[tradeable] =>
[type] => Holiday Hat
)
Private members are just that - private. Only the class they belong to can access them. If you want to be able to retrieve their values, you need to either make them protected (and thus available to parent and children classes) or public (available to all classes). Another option is to write some getters, functions that look like
public function get_slot() {
return $this->slot;
}
or use the __get() magic function to make a general getter that looks like
public function __get($name) {
return $this->$name;
}
More info can be found in the documentation at http://php.net/manual/en/language.oop5.visibility.php
Those items are only accessible by the object itself. You will have to modify the code for that class and provide an accessor method, or change their scope.
http://www.php.net/manual/en/language.oop5.properties.php
You will need accessor method on each object in order to access the values. Since they are private they can only be accessed within each of the classes they belong.
The private properties just can be accessed from inside the object itself. To access try to use $this->propertyName
This answer is for the scenario of trying to get around an imposed private data restriction, for instance if you are by chance working with a library which you don't have access to change the privilege level of the class member, then there is a work around. Presuming the object is serializable/unserializable then consider:
<?php
class SourceProtected {
private $foo = 'one';
protected $baz = 'two';
public $bar = 'three';
}
class SourceUnprotected {
public $foo = 'blah';
public $baz = 'two';
public $bar = 'three';
}
$protected = new SourceProtected();
$unprotected = new SourceUnprotected();
var_dump(serialize($protected), serialize($unprotected));
The output looks something like:
string(110) "O:15:"SourceProtected":3:{s:20:"?SourceProtected?foo";s:3:"one";s:6:"?*?baz";s:3:"two";s:3:"bar";s:5:"three";}"
string(92) "O:17:"SourceUnprotected":3:{s:3:"foo";s:4:"blah";s:3:"baz";s:3:"two";s:3:"bar";s:5:"three";}"
So one solution, is to create a duplicate class that changes the privilege level on the variables to all public. Then serialize the working object, convert*** the serialized class to your versions, then simply unserialize the string and you'll have a working object of your class type with unlimited access.
Obviously the convert method is where you'll have to do some foot work. You'll need to either build a generalized parser which can handle any case or you can code a hacky works just for your specific use case series of str_replaces.
you should see first object oriented php http://www.google.sk/url?sa=t&rct=j&q=object%20oriented%20php&source=web&cd=6&ved=0CGQQFjAF&url=http%3A%2F%2Ftalks.somabo.de%2F200703_montreal_oop.pdf&ei=k3EUT8HnGYHHswbi09A6&usg=AFQjCNEjsA2JgbGQfxnQ26XxTtFuHmvGIA&sig2=Vw4d7aD2GhulZYAM892EKA

Categories