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
Related
I have an object $myObject; I'm trying to return php object as json, but it loses some data. This is how $myObject looks:
CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList Object
(
[priceListId:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 32
[amounts:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 1000
[1] => 2000
[2] => 3000
[3] => 4000
[4] => 5000
[5] => 6000
[6] => 7000
)
[amountsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[1000] => 0
[2000] => 1
[3000] => 2
[4000] => 3
[5000] => 4
[6000] => 5
[7000] => 6
)
[periods:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 10
[1] => 15
[2] => 20
[3] => 25
[4] => 30
)
[periodsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[10] => 0
[15] => 1
[20] => 2
[25] => 3
[30] => 4
)
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 7000
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 30
[prices:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[30] => Array
(
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)
)
)
[settings:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings Object
(
[mode:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => credits
[preset:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] =>
[implementation:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => matrix
[defaults:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => Array
(
[period] =>
[amount] =>
)
)
)
After json_encode($myObject); new data looks like this (screenshot for better json view):
screenshot of returned json
Why information I wrote below is missing and how to access it?
Missing stuff:
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)
The problem is json_encode can not access private properties.
Here are some workarounds you could do:
Convert the properties to be public
You could use a reflection class to convert the properties accessibility before you convert it
Example:
$refObject = new ReflectionObject( $obj );
$refProperty = $refObject->getProperty( 'property' );
$refProperty->setAccessible( true );
You could loop through the properties of the object using a Reflection object and call all the getters converting the object into an array structure that could be easily translated
Refelection Class Documentation
I wish to know how works the laravel 4 relationships in the model. This question is because i'm trying to get the rows from 2 tables with relation and not success till now.
class Products extends Eloquent {
protected $table = "Products";
protected $primaryKey = "ProductId";
public function plandetail()
{
return $this->belongsTo("PlanDetail", "PlanDetail.ProductId")->select( array("ProductId", "Order") );
}
public function getProductsPlan($dealerId)
{
return $this->with( "plandetail" )->where("Products.DealerId", $dealerId)->get();
}
} // end model
// In my controller
$product = new Products();
$products = $product->getProductsPlan($id);
foreach( $products as $product )
{
print_r($product); // prints only the rows from the Products table
// not the PlanDetail table.
}
In the output is just print the product records and not the PlanDetail table rows. Do i need to add a join with the PlanDetail table to get these rows?
This is one example row of what im getting now:
Products Object ( [table:protected] => Products [primaryKey:protected] => ProductId [errors:Products:private] => [rules:Products:private] => Array ( [ProductBaseId] => required|numeric [DealerId] => required|numeric [ProductName] => required|max:255 [DisplayName] => required|max:255 [Bullets] => required [Cost] => required|numeric [SellingPrice] => required|numeric [UseWebServicePricing] => required|boolean [Term] => required|numeric [Type] => required|numeric [Deductible] => required|numeric [VehiclePlan] => required|numeric [Mileage] => required|numeric [TireRotation] => required|numeric [Interval] => required|numeric [UseRangePricing] => required|boolean [IsTaxable] => required|boolean [NotRegulated] => required|boolean [CreatedOn] => required [CreatedBy] => required [ModifiedBy] => required [ModifiedOn] => required ) [connection:protected] => [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [original:protected] => Array ( [ProductId] => 3 [ProductBaseId] => 84 [DealerId] => 50 [ProductName] => Vehicle Service Contract [DisplayName] => US Warranty Service Contract [ProductDescription] => [Bullets] => Warranty Proteccion for the covered components,Rental Car Coverage,Towling Coverage,, [Cost] => 0.0 [SellingPrice] => 0.0 [BrochureImage] => [PDFContrator] => [UseWebServicePricing] => 1 [UseManualPricing] => 0 [BrochureHeight] => 0 [BrochureWidth] => 0 [Term] => 36 [Type] => Platinum [Deductible] => 100 [VehiclePlan] => None [Mileage] => 36000 [TireRotation] => 0 [Interval] => 0 [PENProductId] => 0 [DMSProductId] => 16 [CreatedBy] => GREIVIN BRITTON [CreatedOn] => 2015-01-08 22:26:47.000 [UseRangePricing] => 0 [ModifiedBy] => GREIVIN BRITTON [ModifiedOn] => 2015-01-28 15:06:11.000 [IsTaxable] => 0 [NotRegulated] => 0 ) [relations:protected] => Array ( [plandetail] => ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [fillable:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [softDelete:protected] => )
Thanks in advance :)
It looks like there's a few things wrong here.
The belongsTo method expects the name of the relating model, and then the foreign key of that model on the Products table. It looks like your foreign key is actually on the relating model making this relationship either a hasOne or hasMany. In this case, since you say you are expecting 2 rows, I'm assuming hasMany.
Additionally, the second argument of this only expects the name of the column. It can already guess the name of the table because you gave it the relating model name.
With that in mind, this should be the relationship method you need.
public function plandetails()
{
return $this->hasMany("PlanDetail", "ProductId")->select( array("ProductId", "Order") );
}
And the other function should be modified a bit. When you use with and you need to query based on the relation, you should pass in an array where the key is the name of the relation and the value is a callback function which will allow you to modify the query which will grab the relating items.
public function getProductsPlan($dealerId)
{
return $this->with(array("plandetail", function($q) use ($dealerId)
{
$q->where('DealerID', $dealerId);
}))->get();
}
Now when you do this...
$product = new Products();
$products = $product->getProductsPlan($id);
This should work...
foreach( $products as $product ) {
foreach($product->plandetails as $plandetail) {
print_r($plandetail);
}
}
I also modified the relating function name so you would have to update your getProductsPlan function to reflect that when you use with. When you use hasMany, it makes more sense and is easier to read when you make the function name plural.
I want to retrieve quantities from this array.
invoice Object
(
[data:private] => Array
(
[i_status] => pend
[i_title] => 500 HLCoins , 500 HLCoins x8
[i_member] => 1
[i_items] => Array
(
[0] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 1
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[extra] =>
[opt_id] => 0
[associated] =>
[assocBought] =>
[groupRenewals] => 0
[methods] => Array
(
)
[k] => 0
[_tax] => 0
)
[1] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 8
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[opt_id] => 0
[groupRenewals] => 0
[methods] => Array
(
)
[_tax] => 0
)
)
[i_total] => 0
[i_date] => 1347217384
[i_return_uri] =>
[i_paid] => 0
[i_status_extra] => a:1:{s:4:"type";s:4:"zero";}
[i_discount] => 0
[i_temp] =>
[i_ordersteps] => 0
[i_noreminder] => 1
[i_renewal_ids] => Array
(
)
[i_po] =>
[i_notes] =>
[i_shipaddress] =>
[i_id] => 229
)
[takeAction] => 1
)
I've tried a bunch of codes like $invoice->quantity, $invoice[1]->quantity, $this->$invoice->quantity, but none of them seem to display.
It still does not display at all, I tried to print_r and that is the array it gave me.
All the variables are private which means you cannot access them from outside the object. Check out the class definition for the invoice class. There should be some function to get the quantities from the object, or else you could add such a feature to the class.
The whole point of this is separation of concerns. The class may change in the future and possibly not use the same structure, therefore you should use object functions to access the properties, do not access them directly as variables.
You can read more on this subject in the manual or in a book about object-oriented programming.
Seems like all the data is in a private property. You cannot access it from outside directly.
Read the documentation for the class. It should have some method you can call, like getQuantity(), that'll get you the data. It depends on how the class was written and how it is supposed to be used.
I'm trying to use the stackoverflow API and I want to get answers of a question in a php array. So far here is my php code:
<?php
//KEY
$string = "key=my_key";
//Call stack API .$string
$stack_url = "compress.zlib://http://api.stackoverflow.com/1.1/questions";
//Get and Store API results into a variable
$result = file_get_contents($stack_url);
$jsonArray = json_decode($result);
print_r($jsonArray);
//echo($jsonArray->questions[0]->question_answers_url);
//var_dump($jsonArray);
?>
I want to store the answers of a question in an array called answers so that I can access them with a for loop.
The answer i get is :
stdClass Object
(
[total] => 2618591
[page] => 1
[pagesize] => 30
[questions] => Array
(
[0] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => ssh
[2] => openssh
[3] => rsacryptoserviceprovider
)
[answer_count] => 1
[favorite_count] => 0
[question_timeline_url] => /questions/9164203/timeline
[question_comments_url] => /questions/9164203/comments
[question_answers_url] => /questions/9164203/answers
[question_id] => 9164203
[owner] => stdClass Object
(
[user_id] => 311966
[user_type] => registered
[display_name] => simonc
[reputation] => 301
[email_hash] => 021f3344004f0c886d715314fa02037d
)
[creation_date] => 1328548627
[last_edit_date] => 1328611688
[last_activity_date] => 1328611688
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 25
[score] => 0
[community_owned] =>
[title] => Format of PKCS private keys
)
[1] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => .net
[2] => combobox
)
[answer_count] => 3
[favorite_count] => 0
[question_timeline_url] => /questions/9174765/timeline
[question_comments_url] => /questions/9174765/comments
[question_answers_url] => /questions/9174765/answers
[question_id] => 9174765
[owner] => stdClass Object
(
[user_id] => 1194399
[user_type] => registered
[display_name] => Goxy
[reputation] => 1
[email_hash] => 5fc8c96b6b85c6339cb9ac4ab60cb247
)
[creation_date] => 1328611202
[last_activity_date] => 1328611686
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 15
[score] => 0
[community_owned] =>
[title] => WPF: Bind simple List<myClass> to Combobox
)
....
Not sure exactly which property you want to extract, but I assume it's the 'question_answers_url'.
$answersArray = Array();
for($i=0;$i<count($jsonArray['questions']);$i++){
//assuming it is the 'question_answers_url' property that you want
array_push($answersArray,$jsonArray['questions'][$i]['question_answers_url']);
}
Ought to do it.
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;
}