Part 2 of an in-company training. Complete set of slides under:
Part 1: https://www.slideshare.net/VasilyKartashov/effective-php-part-1
Part 2: https://www.slideshare.net/VasilyKartashov/effective-php-part-2
Part 3: https://www.slideshare.net/VasilyKartashov/effective-php-part-3
Part 4: https://www.slideshare.net/VasilyKartashov/effective-php-part-4
Part 5: https://www.slideshare.net/VasilyKartashov/effective-php-part-5
Part 6: https://www.slideshare.net/VasilyKartashov/effective-php-part-6
More about the author: http://notes.kartashov.com/about/
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.