DeX Posted June 9, 2022 Share Posted June 9, 2022 I'm not sure if I phrased that question properly but I'll give an example: I have a User class and I have a Car class. I have users on a website and they own cars. So if I want to get all users from the database, I use the User class to do that fetch and the same if I want to get all cars from the database. My question is when I want to get all cars owned by a specific person. Should I do something this? $user = new User(123); $carsOwnedByUser = $user->getCars(); Or should I do something like this? $carsOwnedByUser = \CarNameSpace\getCars(123); In the first one I have a function in the User class to get all of their cars and in the second one I have a function in the Car class that gets cars when you pass in a user ID. Is one more proper than the other? Each one will return an array of Car objects. Thanks a lot. Quote Link to comment https://forums.phpfreaks.com/topic/314912-can-data-objects-be-created-from-another-class/ Share on other sites More sharing options...
requinix Posted June 10, 2022 Share Posted June 10, 2022 If you're going with an OOP model (and that's a completely separate discussion) then you should continue with it. Typically the Car class will handle any type of search against its data, meaning that there would be a method like Car::getByUser(user id). In addition to that, you can provide a shorthand from the User class to find that - namely, $user->getCars() that obviously can supply the user ID to getByUser automatically. Quote Link to comment https://forums.phpfreaks.com/topic/314912-can-data-objects-be-created-from-another-class/#findComment-1597178 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.