SlideShare a Scribd company logo
1 of 10
Download to read offline
Effective PHPVasily Kartashov
notes.kartashov.com
Session 2:
Methods Common to All Objects
Implement __toString()
Returns a string representation of an object.
Without __toString
> php -a
Interactive shell
php > class User { public $name; }
php > $user = new User;
php > $user->name = 'Vasily';
php > echo $user;
PHP Catchable fatal error: Object of class User could not be converted
to string in php shell code on line 1 Catchable fatal error: Object of
class User could not be converted to string in php shell code on line 1
Implement __toString()
With __toString
php > class User2 { public $name; public function __toString() { return $this->name; } }
php > $user2 = new User2;
php > $user2->name = 'Vasily';
php > echo $user2;
Vasily
Pros & Cons
➔ A bit more code to write. No universal
representation.
➔ No more “Object User” stuff in logs,
error messages, CLI and other places.
Implement JsonSerializable
Oddly unpaired interface lets you define the shape of your object
during JSON serialization. Paired with factory methods it creates a
nice way to map an object into a structured string representation
and back.
class Version implements JsonSerializable { … }
$version = Version::fromJson($payload);
echo json_encode($version);
Pros & Cons
➔ Mostly marker and syntactic sugar.
➔ Standard way to handle a very
common situation.
Learn to use clone
Bit of an ugly hack, still being used extensively.
Clone creates a shallow copy of a PHP object. It's very often used to
create a immutable objects that fork off a new object every time
there's a modification.
Learn to use clone. Cont’d
Let's assume there's a task object that can be delayed by adding
time to an internal timestamp. The most robust and type safe (but
not the most beautiful) would be
class ForecastUpdateTaks {
private $stationId, $location, $timeHorizon, $time;
public function delay(): ForecastUpdateTask {
$copy = clone $this;
$copy->time += 3600;
return $copy;
}
}
Learn to use clone. Cont’d
This is not changing the original object, robust with regards to
adding new properties to class ForecastUpdateTask, but it's quite
easy to mess up. The clone only creates a very shallow copies, thus
if your class contains a reference to an object, then the reference
will be shared between your original object and the clone.
Pros & Cons
➔ Immutable objects without too much
pain.
➔ Need to be very careful to not create
hidden dependencies between cloned
objects.

More Related Content

What's hot

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 
Object oriented php
Object oriented phpObject oriented php
Object oriented php
jwperry
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
Yi-Huan Chan
 

What's hot (19)

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Object oriented php
Object oriented phpObject oriented php
Object oriented php
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in Laravel
 
Java script basic
Java script basicJava script basic
Java script basic
 
Javascript
JavascriptJavascript
Javascript
 
Os Welton
Os WeltonOs Welton
Os Welton
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in function
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScript
 
Data types in php
Data types in phpData types in php
Data types in php
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in php
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
 
Javascript conditional statements
Javascript conditional statementsJavascript conditional statements
Javascript conditional statements
 
JavaScript infographic - 01
JavaScript infographic - 01JavaScript infographic - 01
JavaScript infographic - 01
 

Similar to Effective PHP. Part 2

Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 

Similar to Effective PHP. Part 2 (20)

Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Design patterns illustrated 010PHP
Design patterns illustrated 010PHPDesign patterns illustrated 010PHP
Design patterns illustrated 010PHP
 
PHP 7
PHP 7PHP 7
PHP 7
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 
Only oop
Only oopOnly oop
Only oop
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
PHPUnit your bug exterminator
PHPUnit your bug exterminatorPHPUnit your bug exterminator
PHPUnit your bug exterminator
 
PhpTour Lyon 2014 - Transparent caching & context aware http cache
PhpTour Lyon 2014 - Transparent caching & context aware http cachePhpTour Lyon 2014 - Transparent caching & context aware http cache
PhpTour Lyon 2014 - Transparent caching & context aware http cache
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

Effective PHP. Part 2

  • 2. Implement __toString() Returns a string representation of an object. Without __toString > php -a Interactive shell php > class User { public $name; } php > $user = new User; php > $user->name = 'Vasily'; php > echo $user; PHP Catchable fatal error: Object of class User could not be converted to string in php shell code on line 1 Catchable fatal error: Object of class User could not be converted to string in php shell code on line 1
  • 3. Implement __toString() With __toString php > class User2 { public $name; public function __toString() { return $this->name; } } php > $user2 = new User2; php > $user2->name = 'Vasily'; php > echo $user2; Vasily
  • 4. Pros & Cons ➔ A bit more code to write. No universal representation. ➔ No more “Object User” stuff in logs, error messages, CLI and other places.
  • 5. Implement JsonSerializable Oddly unpaired interface lets you define the shape of your object during JSON serialization. Paired with factory methods it creates a nice way to map an object into a structured string representation and back. class Version implements JsonSerializable { … } $version = Version::fromJson($payload); echo json_encode($version);
  • 6. Pros & Cons ➔ Mostly marker and syntactic sugar. ➔ Standard way to handle a very common situation.
  • 7. Learn to use clone Bit of an ugly hack, still being used extensively. Clone creates a shallow copy of a PHP object. It's very often used to create a immutable objects that fork off a new object every time there's a modification.
  • 8. Learn to use clone. Cont’d Let's assume there's a task object that can be delayed by adding time to an internal timestamp. The most robust and type safe (but not the most beautiful) would be class ForecastUpdateTaks { private $stationId, $location, $timeHorizon, $time; public function delay(): ForecastUpdateTask { $copy = clone $this; $copy->time += 3600; return $copy; } }
  • 9. Learn to use clone. Cont’d This is not changing the original object, robust with regards to adding new properties to class ForecastUpdateTask, but it's quite easy to mess up. The clone only creates a very shallow copies, thus if your class contains a reference to an object, then the reference will be shared between your original object and the clone.
  • 10. Pros & Cons ➔ Immutable objects without too much pain. ➔ Need to be very careful to not create hidden dependencies between cloned objects.