- Overview
- Transcript
2.5 Copying vs Cloning Objects
Sometimes, it may be useful to create an object from a class and the copy it a couple of times. In that case, it’s good to know how PHP deals with copying. By default, objects are copied by reference, not by value. That’s all fine and dandy, but what does that mean, exactly?
1.Welcome1 lesson, 01:07
1.1Welcome01:07
2.The Absolute Basics of OOP5 lessons, 22:53
2.1What Is OOP?04:40
2.2Classes vs Objects05:42
2.3Class Constants and Internal Reference04:19
2.4Public vs Private Scope06:05
2.5Copying vs Cloning Objects02:07
3.Digging a Little Deeper Into OOP5 lessons, 43:52
3.1The Single Responsibility Principle15:18
3.2Magic Methods11:16
3.3Autoloading Through SPL03:37
3.4Working With Namespaces05:14
3.5Autoloading With PSR-008:27
4.OOP inheritance2 lessons, 12:02
4.1Class Inheritance And Protected Scope09:22
4.2Overriding Parent Methods02:40
5.OOP Abstractions5 lessons, 1:00:05
5.1Abstract Classes05:59
5.2Interfaces14:53
5.3Static Properties And Methods06:49
5.4Traits14:44
5.5Dependency Injection17:40
2.5 Copying vs Cloning Objects
Hello, and welcome back to PHP OOP Fundamentals. In this rather short video, we'll have a look at copying versus cloning objects. Now sometimes it may be useful to create an object from a class. And then copy it a couple of times. In that case, it's good to know how PHP deals with copying. By default, objects are copied by reference, not by value. Now, that's all fine and dandy, you may say. But what does that mean, exactly? Okay, I'll give you an example. Here, we have our user called yost. Now, let's create a brother for yost. We'll just call him Mike, for now. So we'll do Mike equals yost. As simple as that. Now just to see what we're working with, let's just dump both yost and Mike to the screen like so. You see, yost and Mike share exactly the same data. Now because Mike is copy from yost by reference, these two objects remain linked. Watch what happens when I change Mike's email address, like so. We'll just do mike set email mike@touchplus.com. See both yost and Mike's email addresses have changed. And now, watch what happens when I change yost's email address again. Here we go. Yost sets to yost and let's just view that in a browser. Here we go, again, both yost's and Mike's email addresses have changed. So what if i wanted to create a copy from a user, but we want to be able to change only the email address for that specific copy? Well in that case, you need to copy the object by value and you do that by using the word, clone. And now when I say this, yost and Mike are two completely separate objects. Now we've already set Mike's and yost's email addresses to two different values. Let's see how that works out in a browser. See they're not linked anymore. They can have different email addresses, passwords and so on and so forth. Okay that's all for copying versus cloning. I'll see you in the next video which will be about magic methods.







