PHP - What Is The Difference Of These (property Access In Objects)
Hi !
I'm a bit confused about how PHP access to our properties in an object. I've seen these two methods: Code: [Select] $instance->something = 'nothing'; $instance->$something = 'nothing'; what is the difference between them? thanks !! enrique. Similar TutorialsHey Guys.
I have a class named CoreCartFunctions. In the class there is a protected property named $menu_item_id which is initialized as null.
A method named GetMenuItemId assigns the $menu_item_id its value. I have tested it out using the following, to see if a value got returned and it did
fb($menu_item_id->GetMenuItemId(), "This is the menu id");The problem is when I access the property from a different public method in the same class it dones't return anything. fb($menu_item_id->DisplayMenuItems());It only returns something when I hard code a value to it.... Not sure why this is happening. Here is my full code. Please not the example below may have some syntax errors since I just copied and paste pieces of my code, to show a quick and dirty example. class CoreCartFunctions { protected $menu_item_id = NULL; public static $items; //Equal to the a long session string protected function GetMenuItemId() { foreach (self::$items as $menu_item_id_session) { /*********************************** Get the id of the menu item item ************************************/ $this->menu_item_id = preg_match_all('/\-(.*?)\*/',$menu_item_id_session,$match_found)?$match_found[1][0]:""; // The following line shows example of above line // $menu_item_id = "12"; public function DisplayMenuItems(){ return $this->menu_item_id; // Doesn't return Item ID } } Hello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. I have the following three tables (and also delta_point and hist_point which are purposely left out and just mentioned for context). Before going down the Doctrine ORM long curvy road, aggrType was just used to restrict possible values so that I didn't need to use MySQL's ENUM, but now I am thinking there may be value to making it an entity and include some methods (and a second reason because I still can't figure out how to make Doctrine create a FK constraint yet not populate the parent entity with a AggrType object). point -id (int PK) -data -dType /* descriminator. Options are AggregatePoint, DeltaPoint, and HistoricPoint */ aggr_point -id (int PK, FK to point) -aggrType (char FK to aggrType) -data aggrType -type (char PK) /* there are about five types */ I have a service to create a new point based on the provided desired type and user data. I don't like the switch statement to determine which type of point to create, but don't know a better way. Also my entity is responsible to provide the appropriate validation rules for the given point type which might not be considered proper but it seems to work for me. Any constructive criticism is welcomed. <?php namespace NotionCommotion\PointMapper\Api\Point; use NotionCommotion\PointMapper\Domain\Entity\Point; class PointService { public function create(string $type, array $params):integer { $class=[ 'aggr'=>'AggregatePoint', 'delta'=>'DeltaPoint', 'hist'=>'HistoricPoint', ][$type]; //$class='Point\\'.$class; //This doesn't seem to be possible and I needed to use the fully qualifed name without the short cut used namespace. $class='\\Greenbean\Datalogger\Domain\Entity\Point\\'.$class; $point=new $class(); $validator=$this->getValidator($point); $params=$validator->sanitize($params); $validator->validate($params); $point->setAccount($this->account); $point->populate($params, $this->em); //Will be addressed later $this->em->persist($point); $this->em->flush(); $point->setIdPublic($this->em->getRepository(Point\Point::class)->getPublicId($point->getId())); return $point->getIdPublic(); } } Now, this is the part I am struggling with the most. I only have one service to create any type of point, so I do wish to put a bunch of if/thens in it and instead move logic to the individual point type being created. The AggrPoint in question requires a sub-point and I don't think it is appropriate to inject the entity manager into a point entity and as an alternative solution find an existing point which is associated with the account which resides in the new AggrPoint. Maybe not appropriate, but it works. This type of point also has a sub-object AggrType as discussed at the very beginning of this post, so I first attempt to create a new one from scratch, but that doesn't work and I need to set $aggrType with an existing one. As an alternative, I passed the entity the entity manager, but as stated I think this is a bad idea. Any recommendations where to go from here? Thank you namespace NotionCommotion\PointMapper\Domain\Entity\Point; class AggregatePoint extends Point { public function populate(array $params, \Doctrine\ORM\EntityManager $em):\NotionCommotion\PointMapper\Domain\Entity\Entity{ $criteria = \Doctrine\Common\Collections\Criteria::create() ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("id_public", $params['pointId'])); if(!$subpoint = $this->getAccount()->getPoints()->matching($criteria)->current()){ throw new \Exception("Invalid subpoint ID $params[pointId]"); } $this->setSubpoint($subpoint); //This won't work since I must use an existing AggregateType and not create a new one $aggrType=new AggregateType(); $aggrType->setType($params['aggrType']); //This just seems wrong and I shouldn't be passing the entity manager to an entity $aggrType=$em->getRepository(AggregateType::class)->findOneBy(['type'=>$params['aggrType']]); $this->setAggregateType($aggrType); unset($params['pointId'], $params['aggrType']); // parent::populate($params) not shown, but it basically calles appropriate setters based on the property name return parent::populate($params); } public function getValidatorRules():array { return $this->filesToArr(['/point/base.json', '/point/aggr.json']); } }
Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble if the price of a book is less than $20.00 output the book’s name and price if the book’s title comes after the letter R in the alphabet output the book’s title. I am getting these error:
Notice: Trying to get property 'price' of non-object in C:\xampp\htdocs\PHP objects\books.php on line 45 My code is:
<?php
// Methods
$first_book = new Book();
foreach ($book as $bookItem) { Any help will be very much appreciated Thank you I am working with wordpress and I see a lot of "if" statements done like this if(condition): do something endif; I have always done it like so if(condition) { do something } what is the difference? does the first method have any advantages over the second method? Hi, In Php , What is the different ebtween abc() and @abc() ??? Please advice . Actually what's the difference between Code: [Select] if(...) and Code: [Select] if(isset(...) This is going to seem like a stupid question but I'm curious about it anyway. Isn't isset and !empty do the same? Considering security, is there a disadvantage in using $_REQUEST? Hi all,
I am working with the following 2 page script: https://github.com/k...hi/php-riot-api. All works well and the data is pulled via the API as intended. However, depending on the data I'm trying to display on screen, the object contains multiple values.
For example:
$r = $test->getSummoner($summoner_id,'name'); print_r($r);outputs their ID and name: {"585897":"TheirName"} Just as the following: $r = $test->getSummonerByName($summoner_name); print_r($r);outputs username, ID, Name, profile icon ID, level, and timestamp: {"theirname":{"id":585897,"name":"TheirName","profileIconId":642,"summonerLevel":30,"revisionDate":1405652924000}} Depending on which function I am calling (on example.php), I would like to be able to split the values so I can echo them throughout a page: Name: <value> ID: <value> Level: <value> etc... Any guidance would be appreciated. In a relational database, you "link" tables together. For example, Customer (parent) ---> Product (child) How do you do that with Objects? I have a "User" class and an "AddressBook" class. A User can have zero or more Addresses (in their AddressBook). If I create a User object and an AddressBook object, I need a way to link them up similar to how they are linked up in the database. Make sense?! TomTees I know it is often frivolous, but sometimes I can't help trying to optimize things, and use the following two methods to create either an object injected with a string or one of a set of objects. For both cases, the class has no setters so there is no chance that the object will later be changed. I first stated doing this in continuously running server applications which I believe makes sense, however, it has leaked over to standard HTTP requests. Please commit good or bad on this approach. Thanks
public static function create(string $unit):self { static $stack=[]; if(!isset($stack[$unit])) { $stack[$unit] = new self($unit); } return $stack[$unit]; } public static function create(string $class):FunctionInterface { static $stack=[]; if(!isset($stack[$class])) { $stack[$class] = new $class; } return $stack[$class]; }
I took an object, and saved it into a database serialized. Code: [Select] $object_here = serialize($theobject); Then later on, I go and I get that data from a database, and try to unserialize it.. Code: [Select] $objecthere = unserialize($row->theobject) And it throws the following error...any advice? Quote Warning: unserialize() [function.unserialize]: Node no longer exists in /path/to/file on line 20 I found it helpful to configure all my objects in one or several bootstrap scripts. Before doing so, I would often find myself forgetting that I already had written some class which is located deep in some script and recreating it for some other need (granted, composer definitely helped in this regard, but using it wasn't always applicable). <?php $c=new Pimple\Container(getMySettings()); $c['pdo'] = function ($c) { $db = $c['settings']['mysql']; return new \PDO(bla); }; $c['foo'] = function ($c) { return new Foo( $c->get('pdo') ); }; $c['bar'] = function ($c) { return new Bar( $c->get('foo') ); }; It is all good until I find myself needing to create some new instance of some class instead of just passing some common instance to whoever needs it. class Foo { private $pdo; public function __construct(\PDO $pdo) { $this->pdo=$pdo; } public function getSomething():SomeClass { return new SomeClass($this->getAllDataFromDB($GET['id'])); } } class SomeClass { private $arr; public function __construct(array $records) { foreach($records as $record) { $arr[]=new SomeOtherClass($record); } } } I've read that one shouldn't create new objects in a given class's constructor, and while I could instead do so in some class's method and pass the object to the given class's constructor, to me it seems to really be the same thing. The three issues I have with this scenario a Needing to remember that these classes exist as they are hidden deep in some classes. Makes it more difficult to replace one of the classes with some other class in the future. Some duplication of code.Are there other compelling reasons not to do so? Is it worth the effort to do differently? If so, how would you recommend doing so? My thoughts would either to use Pimple's factory() method are create my only factory which also relies on anonymous functions. Maybe something else? $c['someClass'] = $c->factory(function (array $record, Container $c) { return new SomeClass($record); }); Thanks hiii, Im wanting to calculate the time difference between $out2 and $in2 and out put it into a spreadsheet: Code: [Select] $m=0; while ($m < $num9) { $fullname=mysql_result($result9,$m,"username"); $date=mysql_result($result9,$m,"date"); $in1=mysql_result($result9,$m,"in1"); $out1=mysql_result($result9,$m,"out1"); $in2=mysql_result($result9,$m,"in2"); $out2=mysql_result($result9,$m,"out2"); $out2f=date("G:i:s",strtotime($out2)); $in2f=date("G:i:s",strtotime($in2)); echo date("D",strtotime($date)). "\t" . $fullname . "\t" . $in1 . "\t". $out1 . "\t" . $in2 . "\t" . $out2 . "\t" . date("G:i:s",strtotime($out2f-$in2f)) . "\t" . "\n"; $m++; } header("Content-disposition: attachment; filename=spreadsheet.xls"); why does this code return 00:00:00 ? i have searched everywhere and no code seems to work. i have time1 and time 2 in the format Y-m-d H:i:s. i just don't know how to find the difference. old time: 2011-04-11 20:15:46 new time: 2011-04-11 21:00:11 after i have the difference, i need to get a resource production per hour which is stored in the database and calculate the new value of the resource. $production_per_hour = 100; $time_old = "2011-04-11 20:15:46"; $time_new = "2011-04-11 21:00:11"; $current_resources = "500"; <?php $i = 2; $i = $i++; echo $i; ?>Output of above code is 2. <?php $i = 2; $p = $i++; echo $i; ?>Output of above code is 3. Why this difference? I mean how these codes are processed to give an output? Basically I am using DATETIME to store the time in which a row was input. Format - 2010-11-13 21:31:53 How would I get the current time of page load and compare it to the database row "2010-11-13 21:31:53" then output the difference. Example $sqlresult = 2010-11-13 21:31:53; $currentTime = (GET CURRENT DATE+TIME = (2010-11-13 21:31:55) ); Output - This was posted 2 minute's ago. Thank you in advance. Any help would be greatly appreciated. I'm trying to subtract get the total number of days between two dates. I have been trying the DateTime date_diff method and the strtotime methods. I have it working mostly; but I have a problem with if the value should be negative. I've tried the invert() on the value that comes back from the date_diff() function but get errors. To sum up what I'm trying to do is:
if ( $diff === 0 ) //retrieve expected complete time if ( isset( $stat[ 'expected_complete_time' ] ) ) { $today = new DateTime("now"); $expected_complete_time = new DateTime($stat[ 'expected_complete_time' ]); $today->setTime(12, 0, 0); $expected_complete_time->setTime(12, 0, 0); //calculate difference $eta = date_diff($expected_complete_time, $today)->format("%d");; //future if ($today > $expected_complete_time) { $eta = '+' . $eta; //today } elseif ($eta === '0') { $eta = 'Today'; //overdue } else { $eta = 'LATE:-' . $eta; } } else $eta = '';
|