As the title suggests, I created a base class named member which I want to use to get some basic information, but for some reason, I cannot seem to access those methods/values from the child class named user_send_message

Here is the complete code that I have made so far --

# Base class to build all other user classes off of.

class member{

    var $username;
    var $dob;
    var $city;
    var $state;
    var $zip;
    var $about_me;
    var $photo;
    var $gender;
    var $lookgender;
    var $min_age;           # Minimum age of this user's potential matches
    var $max_age;           # Max age of potential matches
    var $signup_date;       # date that user signed up
    var $level;             # Is member a free or premium member?
    var $premium_start;     # Date that payment for premium membership was recieved
    var $premium_end;       # Date that premium membership ends

    public function member()
    {

        $q = mysql_query(" SELECT * FROM user WHERE username = '". mysql_real_escape_string(htmlentities($_REQUEST['member'])) ."' ");

        # Lets do some verification -- the above query was sanitized, now let's add some extra insurance
        $count = mysql_num_rows($q);
        if($count != 1){
        echo "<div class=error>This user does not exist, or an unknown error has occured.</div>";
        header('location: 404.html');
        exit;
        }

        $member = mysql_fetch_assoc($q);
        # Get the photo
        $p = mysql_query(" SELECT picture FROM usersnaps WHERE username = '" . mysql_real_escape_string(htmlentities($_REQUEST['member'])) . "' ");
        $pic = mysql_fetch_assoc($p);   

        $this->photo = "<img class=viewprofile src = http://localhost/fling/" . $pic['picture'] . ">";
        $this->username = $member['username'];  
        $this->city = $member['city'];
        $this->state = $member['state'];
        $this->zip = $member['zip'];
        $this->dob = $member['birth_date'];
        $this->about_me = $member['about_me'];
        $this->gender = $member['gender'];
        $this->lookgender = $member['lookgender'];
        $this->min_age = $member['lookagestart'];
        $this->max_age = $member['lookageend'];
        $this->signup_date = $member['regdate'];
        $this->level = $member['level'];
        $this->premium_start = $member['premium_start'];
        $this->premium_end = $member['premium_end'];
    }

    # A function using the date of birth to figure out a user's age
    public function age_from_dob($dob) 
    {

        list($y,$m,$d) = explode('-', $this->dob);
        if (($m = (date('m') - $m)) < 0) {
            $y++;
        } elseif ($m == 0 && date('d') - $d < 0) {
            $y++;
        }

        echo date('Y') - $y;
    }
}


# A class that will check whether a member is allowed to contact another member by checking the recipient's contact settings from the user_preferences table

class user_send_message extends member{

    # Some of the preferences such as min_age can be inherited from the user class...so just need to get the rest from user_preferences now

    var $marital;
    var $smoker;
    var $kids;

    public function user_send_message(){

        # First, let's get the recipient's preferences
        $query = mysql_query(" SELECT marital_status, smoker, kids FROM user_preferences WHERE username = '". $_REQUEST['member'] ."' ");
        $m = mysql_fetch_assoc($query);

        $this->kids = $m['kids'];
        $this->marital = $m['marital_status'];
        $this->smoker = $m['smoker'];

        # Now, we need to compare the sender's information to make sure it conforms with the information above


    }
}

The $_REQUEST['member'] in the SQL queries just get the variable "member" from the URL ( example: send-message.php?member=mariah )

But when I try to use the user_send_message class, I cant seem to access the values from the parent class...can anyone see what is going wrong?

Thank you very much for any help!

You can't use $_REQUEST, $_POST or $_GET in classes, you need to send that information from the page that is getting that information by instantiating the class in that page. Can you post the code where you are using the class and methods.

Sure thing, here is a page where you view the member's profile:

<?php $v = new member; ?>

<table>
<tr><td><?php echo $v->photo; ?></td>
<td>
<strong>Username:</strong> <?php echo $v->username; ?>
<strong>Location:</strong> <?php echo $v->city . ", " . $v->state; ?>
<strong>Age:</strong> <?php echo $v->age_from_dob($dob); ?>
<strong>About Me:</strong> <?php echo $v->about_me; ?>
</td></tr>
</table>

<a href="send-message.php?member=<?php echo $v->username; ?>">Send Message</a>

This page works perfectly fine when I use the member class (the base class),
but if I try to use the user_send_message class then I'll get a blank page..

I didn't realize that you cannot use Get Post or Request -- I assume that you mean that you cannot use them in child classes? (since I use it in the base class and it works as intended)

To understand what is going wrong in your code, you need to have an access to the php's error's messages.
So firstable, if don't have access to your php.ini and/or you don't want to modify it, you can set the error's display with that :

error_reporting(E_ALL);
ini_set('display_errors', '1');

it may avoid the blank page and display what's not good in your script.

So if you want to use the child class as object you need to instanciate it :

replace that line :
<?php $v = new member; ?>
with :
<?php $v = new user_send_message; ?>

hope to help you.

Hi jerome,

Thank you for your advice...
however, changing the code:

<?php $v = new member; ?>
with :
<?php $v = new user_send_message; ?>

is where I am having my issues.

As an example, if I instanciate the member base class, I can run this with no problem:

echo $v->username

and it will print out the username correctly.

However, if I instantiate the user_send_message child class, trying to print $v->username does not produce anything.
The only clue to solving this is that $v->username is blank when it is printed out, but the rest of the script is unaffected...

I did enable error reporting using the code you supplied, but the only error reported was the following regarding session_start():

Notice: A session had already been started - ignoring session_start() in C:\wamp\www\fling\libs\definitions.php on line 1

The lady who first responded to the thread informed me that I cant use GET / POST / REQUEST inside a class; could this be the cause of the problem?

I do have a workaround, where in the child class I redeclare some variables from the base class, but that pretty much defeats the purpose of classes and inheritance...I'm still on training wheels when it comes to OOP, so even though I technically have this working now, I want to learn and figure out the correct way to do things and why the code above doesnt work.

Thanks for everyone's patience and help!

Hi,

Try this :

index.php :

<?php

    include_once 'member.php'; // we include the member class

    $v = new member('bill'); 
    // we create an instance of the member class 
    // here we indicate the user name : bill
    // we can use $_REQUEST, $_POST, $_GET, $_SESSION, ... to get user name

 ?>

<table>
    <tr>
        <td><?php echo $v->photo; ?></td>
        <td><strong>Username : </strong> <?php echo $v->username; ?>
            <strong>Location : </strong> <?php echo $v->city . ", " . $v->state; ?>
            <strong>Age : </strong> <?php echo $v->age_from_dob($dob); ?>
            <strong>About Me : </strong> <?php echo $v->about_me; ?>
        </td>
    </tr>
</table>
<a href="send_message.php?member=<?php echo $v->username; ?>">Send Message</a>

member.php (member class) :

<?php

class member{

    var $username;
    var $dob;
    // ... your other vars

    public function member($member_name) // here we get member's name
    {
        $this->username = $member_name;

        $q = mysql_query(" 
            SELECT u.*, n.picture 
            FROM user as u, usersnaps as n 
            WHERE u.username = '". mysql_real_escape_string(htmlentities($this->username)) ."' and n.username = u.username
        ");     
        // here we can use a single mysql request to get all member's data

        $count = mysql_num_rows($q);
        if($count != 1){
            echo "<div class='error'> This user does not exist, or an unknown error has occured. </div>";
            // header('location: 404.html'); 
            // here we must choose, it should display a message or a page containing a message, but not both at the same time.
            exit;
        }

        $member = mysql_fetch_assoc($q); 

        $this->photo = "<img class=viewprofile src = http://localhost/fling/" . $member['picture'] . ">";
        $this->username = $member['username'];  

        // ...
        // your other attributes here
        // ...

    }
    public function age_from_dob($dob) 
    {
        // your function code here
        // use a return to return the result
    }
}

user_send_message.php (user_send_message class) :

<?php

include_once 'member.php';

class user_send_message extends member{

    var $marital;
    var $smoker;
    var $kids;

    public function user_send_message($member_name){

        $query = mysql_query("SELECT marital_status, smoker, kids FROM user_preferences WHERE username = '". $member_name ."' ");

        if($m = mysql_fetch_assoc($query)){
            $this->kids = $m['kids'];
            $this->marital = $m['marital_status'];
            $this->smoker = $m['smoker'];
        }

    }
}

send_message.php :

<?php

include_once 'user_send_message.php';

$username = $_GET['member']; // get the member name

$message = new user_send_message($username);

Try this and tell me if you have any problem.

Hi,

This is not a direct response to your questions. I can rewrite your entire codes to make it functional if I want to. However, I don't want to deprive people from the wonders and benefits of learning.

Below is the simplest SAMPLE codes I could come up with inheritance. In fact, I have created two child classes.

<?php
    class Member{
     ## you can use these 
        //var $name= null;
        //var $lname = null;
        //var $age = null;
        //var $sex = null;

        ## or set them as public
        public $name= null;
        public $lname = null;
        public $age = null;
        public $sex = null;

        ## if you don't want a constructor in the child class, then you can include all variable above as an arguments below.
        public function __construct($name,$lname,$age,$sex){
            $this->name = $name;
            $this->lname = $lname;
            $this->age = $age;
            $this->sex = $sex;
        }

        public function getName(){
            return $this->name;
        }

        public function getlname(){
            return $this->lname;
        }

    }

    ## extend the parent class above without the constructor
    class Age extends Member{


        public function getAge(){
         return $this->age;

        }
    }
    ## extend the parent member class above without constructor
    class Sex extends Member{
        public function getSex(){
            return $this->sex;
        }
    }

    ## instantiate the child class Age
    $membersAge = new Age('Name','lname','20','male');

    echo "Age: ".$membersAge->getAge()."<br/>";

    ## instantiate the child class Sex
    $memberSex = new Sex('Name','lname','20','male');
    echo "Sex: ". $memberSex->getSex();

    ## instantiate the parent
    $membersData = new Member('Name','lname','20','male');
    echo "<br/> Name: ".$membersData->getName()."<br/>";
    echo "Last Name: ".$membersData->getLname()."<br/>";
?>

In contrast to some beliefs, Yes you can process $_GET, $_REQUEST, and $_POST within the class. As shown by my simple singleton pattern example below..

Looking at the codes closely, the arguments are coming from the submitted form data..

!WARNING! script below is not intended for use in production server.

<?php

    class ProcessForm{
        ## somehow my mood is to write a simple demonstration of singleton pattern for this class
        public static $instance = NULL;
        ## in singleton pattern we set the constructor as private
        private function __construct(){
    }
       ## public static function to check if the process form class has been instantiated
       public static function getInstance() {
        ## if there is no instance of an ProcessForm, we instantiate it here
        if(!isset(self::$instance)) {
          self::$instance = new ProcessForm();
        }
        ## we return this instance
        return self::$instance;

      }

       public function checkFormSubmit(){
        if(isset($_POST['submit'])&&(!(empty($_POST['name'])))){
            return true;
        }
        else{

            return false;
        }
    }
        public function getFormData(){
        if(self::checkFormSubmit()){
            $this->name = $_POST['name'];
            $this->lname = $_POST['lname'];
            return array($this->name, $this->lname);
        }

    }

    }


$checkform = ProcessForm::getInstance();
if($checkform->checkFormSubmit()){
    $name = $checkform->getFormData();
    echo $name[0]."<br/>";
    echo $name[1]."<br/>";
}
else{
?>

<form method="post" action="">
<label>Name</label>
<input type='text' name='name'>
<br/>
<label>Last Name</label>
<input type="text" name="lname">
<br>
<input type="submit" name="submit" value="submit">
</form>

<?php
}
?>

akmozo,
Not sure what happened to my previous response to you, but I wanted to make sure that I thanked you for your insight. Seeing your changes to the SQL queries and the overall flow of the script really helps me think of different ways to approach a problem...I think that your reproduction of my script is much superior, and is very helpful to me improving my understanding of general PHP programming, not just OOP.

Lets’ simplify your code and give an example of what is happening in the comments of the code

<?php
class member
{
  // Why don't you declare if it the visibility of var e.g. public ? 
  // Yes PHP will made it public , but it's best to declare the visibility
  var $username;

  // Don't use such constructors in PHP ... It isn't a good idea and from PHP 5.3.3 
  // is not supported in namespaced classes. The PHP way is __construct() 
  public function member()
  {
    $this->username = "example";  
  }  
}

class user_send_message extends member
{
  var $marital;

  // The same as above. In PHP a constructor overides parent contstructors 
  public function user_send_message()
  {
    $this->marital = false; 
  }
}

$member = new member();
var_dump($member->username);
// of course will output example 

$newMember = new user_send_message(); 
var_dump($newMember->username);
// of course will output null 
?>
<br/>
The clean way I am proposing ...  
<br/>
<?php
class member2
{
  public $username;

  public function __construct()
  {
    $this->username = "example";  
  }  
}

class user_send_message2 extends member2
{
  public $marital;

  public function __construct()
  {
    parent::__construct();
    $this->marital = false; 
  }
}

$member2 = new member2();
var_dump($member2->username);
// of course will output example 

$newMember2 = new user_send_message2(); 
var_dump($newMember2->username);
// of course will output example .... 
?>

For the sake of learning.

I think you're whole architecture and thought process on this is wrong.
There is a complete violation of single responsibility in all of your classes.

We can quickly break this into three responsibilities.

  1. Entity\Member - an entity which models a member
  2. Validator\Contact - a class which handles validating if two members can communicate
  3. Entity\Message - an entity which models a message

Example\Entity\Member.php

<?php

namespace Example\Entity;

class Member
{
    //Properties and methods representing a single unique member.
}

Example\Validator\Contact.php

<?php

namespace Example\Validator;

use Example\Entity\Member;

class Contact
{
    public function validate( Member $from, Member $to )
    {
        $communicate = false;

        //Logic that looks at both members and determines if they can communicate.
        //Sets communicate to true/false depending on results of logic

        return $communicate;
    }
}

Example\Entity\Message.php

<?php

namespace Example\Entity;

use Example\Entity\Member;

class Message
{
    //Properties and methods representing a single unique message
    //Should all for a to and from to be set

    protected $to;
    protected $from;

    setTo( Member $to ){
        $this->to = $to;
        return $this;
    }

    // Etc.

    send(){
        //Violates single responsibility but just used for illustration.
    }
}

Usage Example:

<?php
//Example\index.php

namespace Example;

use Example\Entity\Member;
use Example\Entity\Message;
use Example\Validator\Contact;

$memberFrom = new Member();
$memberTo = new Member();

$validator = new Contact();

if( $validator->validate( $memberFrom, $memberTo ) ){
    $message = new Message();
    $message->setFrom( $memberFrom );
    $message->setTo( $memberTo );
    $message->setBody( 'lorem ipsum' );
    $message->send();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.