/    Sign up×
Community /Pin to ProfileBookmark

Good Morning,

I only have basic skills in procedural coding in PHP but am trying to get into Object Oriented.

I have a question, If I had a class called person (to keep it generic). I can create a person object from a form submission, such as $person = new person($_POST[]…);

Can I have a method in my class called getPersonFromID() which creates the person within the class?

$personObject = new Person;
$person = $personObject->getPersonFromID(44);

Does this work or should I have another class to retrieve and create people from places like a database?

Thank you and I am learning.

to post a comment
PHP

6 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 10.2021 — I would say just one Person class, and it would include 2 public methods for those 2 cases, maybe Person::create() and Person::get(). Part of create() would probably be to populate a class property with the database ID upon successful creation, whereas the get() method would presumably be getting that as a method parameter. I _might_ consider adding the ID as an optional argument to the constructor:
[code=php]
class Person {
private $id;
private $pdo;
public function __construct(PDO $pdo, $id = null) {
$this->pdo = $pdo; // I like to pass DB objects in, not create within a class
if(!empty($id)) {
$this->get($id);
}
}
public function get($id) {
// stuff here to query database and populate relevant class properties
}
public function create(Array $data) {
// stuff here to create new person in DB and populate any relevant class properties
}
}
[/code]
Copy linkTweet thisAlerts:
@singaporeDudeauthorNov 11.2021 — Can you also create a list of itself then? Something lie this?

<i>
</i> public function getPeople($group, $id){
$peopleList = array();
$Db = dbh::connect();;
$con = $Db-&gt;getConnection();
$sql = "SELECT * FROM <span><code>people</code></span> WHERE <span><code>group</code></span>= ? AND <span><code>id</code></span> = ?";
$stmt = $con-&gt;prepare($sql);
$stmt-&gt;bind_param('ii', $group, $id);
$stmt-&gt;execute();
$result = $stmt-&gt;get_result();
while($row = $result-&gt;fetch_assoc()){ <br/>
$people= $this-&gt;create($row['id']......);
$peopleList[] = $people;
}

<i> </i> return $peopleList;
<i> </i>}
<i> </i>
Copy linkTweet thisAlerts:
@NogDogNov 11.2021 — I would probably (could be argued out of it, maybe) create a separate class for groups of Person objects, probably implementing either the [Traversable](https://www.php.net/manual/en/class.traversable.php) or [Iterator](https://www.php.net/manual/en/class.iterator.php) interface. Then you'd basically do what you're saying, maybe something like:
[code=php]
class PersonGroup implements Iterator {
private $people = [];
public function __construct($group, $id){
$this->getPeople($group, $id);
}
private function getPeople($group, $id) {
// search stuff, then with results:
while($row = $result->fetch_assoc()) {
$this->people[] = new Person($id);
}
}
// The following are Iterator interface methods:
public function current() {
return current($this->people);
}
public function key() {
return key($this->people);
}
public function next() {
return next($this->people);
}
public function rewind() {
return reset($this->people);
}
public function valid() {
return isset($this->people[current($this->people)]);
}
}
[/code]

No guarantees on any of that code, just throwing a quick-and-dirty mock-up together. The iterator stuff would then mean that you could do foreach() loops on the Person objects it contains, something like:
[code=php]
$group = new PersonGroup($group, $id);
foreach($group as $person) {
// do stuff with $person, which will be a Person object
}
[/code]
Copy linkTweet thisAlerts:
@singaporeDudeauthorNov 11.2021 — How would you manage an exemption if no objects are returned in your db query?

Assuming you would do something like

<i>
</i>$person = new people;
$person-&gt;getPeople(12,23);
..

echo $person-&gt;showPersonName();


If the getPeople method returned no results I'd get the "must not be accessed before initialization" error. Is there a way to manage this within the class or should I somehow check this prior to echo'ing out a name.
Copy linkTweet thisAlerts:
@NogDogNov 12.2021 — Hmm...I _think_ maybe you could just leverage that valid() method -- well, the one I modified a bit in this test code. :)
[code=php]
<?php
class Person {
private $id;
public function __construct($id) {
$this->id = (int) $id;
}
}

Class PersonGroup implements Iterator {
private $people = [];
public function add(Person $person) {
$this->people[] = $person;
}
// Iterator methods:
public function current() {
return current($this->people);
}
public function key() {
return key($this->people);
}
public function next() {
return next($this->people);
}
public function rewind() {
return reset($this->people);
}
public function valid() {
return is_int($this->key());
}
}

$test = new PersonGroup();
$result = $test->valid();
echo "Unpopulated valid() check: ".var_export($result, 1)."n";

$test->add(new Person(123));
$test->add(new Person(456));
$result = $test->valid();
echo "Populated valid() check: ".var_export($result, 1)."n";

foreach($test as $person) {
var_export($person);
echo "n";
}
[/code]

Output:
<i>
</i>$ php test.php
Unpopulated valid() check: false
Populated valid() check: true
Person::__set_state(array(
'id' =&gt; 123,
))
Person::__set_state(array(
'id' =&gt; 456,
))

So, if valid() returns false, you know you have an empty array, and you can then decide what to do in that case.
Copy linkTweet thisAlerts:
@singaporeDudeauthorNov 12.2021 — That works for lists of object but what it the class was designed for a single instance?

Is there a was of tell if it's been initiated or if it's empty? I would have thought isset would be the answer but it appears not.

Many thanks
×

Success!

Help @singaporeDude 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.27,
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,
)...