/    Sign up×
Community /Pin to ProfileBookmark

OOP – Instance of an object

So I’m playing around with OOP in PHP. I only do this part time, a few times per week so excuse me if this is a dumb question.

If for example I have a person class.

When a form is submitted I create a new instance of that person

“`$Person = new Person($_POST[‘personaName’]);“`

For example.

And within the Person Class I have a constructor;

“`
public function __construct($personName){
$personName = $personName;
}
“`

However, If I want to get a person from my database. How can I do something like

“`
$PersonClass = new Person;
$Person = $PersonClass->searchById($_GET[‘ID’]);
“`

Where this method looks up the person in my database and creates them?

Does this second class need be just that, a complete second class which constructs and returns the Person?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 30.2020 — I think I'd remove the population via the constructor, and instead add create() and read() methods (or whatever you prefer to call them), keeping everything in one class -- and eventually you may want to add update() and delete() methods to complete the typical "CRUD" quartet.
<i>
</i>class Person {
public function create($name) {
// do whatever you do when you create from name
}

public function readById($id) {
// populate from DB with ID
}
}

$person1 = new Person();
$person1-&gt;create($_POST['personName']);

$person2 = new Person();
$person2-&gt;readById($_GET['ID']);
Copy linkTweet thisAlerts:
@NogDogNov 30.2020 — PS: I think you might be able to do this, just to save a line of code. (I can't test it just now, but am curious if it works. :) )
<i>
</i>$person1 = (new Person)-&gt;create($_POST['personName']);
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.8,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...