Note that there are some explanatory texts on larger screens.

plurals
  1. POSet subclass of object when parent class is constructed (dynamic sub-classes)
    primarykey
    data
    text
    <p>EDIT: To clear up some confusion, I am not actually using <code>Male</code> and <code>Female</code>. A better example would be parent-class <code>Animal</code> and sub-classes <code>Cat</code> and <code>Dog</code>.<br> I'm kind of new to OOP, but I've grasped it pretty well so far. However, there's one thing I can quite find a way of doing.<br> Firstly, I create a create a new object based around the user. The user can be be (for this example) male or female, but I cannot check if they are without checking in the database. I then need to create a new user object with the sub-class of their sex.<br> For example, here is my current (messy) code:</p> <pre><code>$user = new Person(); $userType = $user-&gt;GetUserType($userid); if ($userType == 'Male') { $user = new Male($userid); } else { $user = new Female($userid); } </code></pre> <p>If I want to make a new object, I must do this every time, which is something I don't want to have to do.<br> Here's a little more code to help put this into perspective:</p> <pre><code>class Person { function GetUserType($userid) { $db = mysqlConnect(); $stmt = $db-&gt;stmt_init(); // Get the players information $stmt-&gt;prepare("SELECT user_type FROM user_information WHERE user_id = ?"); $stmt-&gt;bind_param('i', $userid); $stmt-&gt;execute(); $stmt-&gt;bind_result($userType); $stmt-&gt;fetch(); $stmt-&gt;close(); $db-&gt;close(); return $userType; } } class Male extends Person { // Male based things here } class Female extends Person { // Female based things here } </code></pre> <p>So, in the <code>__construct</code> of the <code>Person</code> class, I'd like it to check for the users sex and set the appropriate sub-class.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload