Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

OOP in PHP, just learning, but confused.

Status
Not open for further replies.

peterv12

Technical User
Joined
Dec 31, 2008
Messages
108
Location
US
I want to learn OOP, and I found an article online that shows some PHP OOP examples. When I copy them and attempt to run them, I get the following error:
Code:
[COLOR=red][b]Fatal error: Cannot access empty property in /Users/peterv/Sites/PROJECT3/index.php on line 13[/b][/color]
I have the following two scripts, the first one titled index.php:
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>OOP Test Project</title>
    </head>
    <body>
        <?php
        include "Student.php";

        $a_student = new Student("John","Male");

        print $a_student->$Name;

        ?>
    </body>
</html>
The second script is:
Code:
<?php

class Student {
    var $Name;
    var $Gender;
    
/* Constructor */
function Student($studentName, $studentGender) {
    $this->Name=$studentName;
    $this->Gender=$studentGender;
}

}
?>

The way I understand it is the index.php script should call the Student.php class (second script) passing it two variables, and Student.php should print the values in a web page, but all I get is the error message. I'm new to OOP, so I may be totally off base by how this should be coded, I'm just going by the article I found on the web. Any help, or explanations will be greatly appreciated!
 
Code:
print $a_student->[red]$[/red]Name;
This reads as: take the variable $Name, use its contents as a string and use this as the property name of the property to print.
Code:
print $a_student->Name;
Would work. Note that you are using PHP4 syntax, and PHP4 is already end-of-life. What's more, you use a variable within an object directly, thereby denying the object the responsibility for it. Object orientation is all about responsibility. So even for "just a variable" you would write a function that returns it. That function could just pass the variable, or even lazily initialize it. That choice is internal to the object and therefore encapsulated.


+++ Despite being wrong in every important aspect, that is a very good analogy +++
Hex (in Darwin's Watch)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top