+skyler_sdf Posted December 4, 2011 Report Posted December 4, 2011 One way in which our TextBox class is not very useful is that its instances do not contain any data when they are created, except for the static initialization of the variable $body_text. The point of such a class would be to display arbitrary pieces of text, not the same message every time. It's true that we could make an instance and then install the right data in the instance's internal variables, like so: $box=new TextBoxSimple; $box->body_text="custom text"; $box->display(); The correct way to arrange for data to be appropriately initialized is by writting a constructor function- a special function called__construct(), which will be called automatically whenever a new instance is created. Example: ?php class TextBox{ var $body_text="my text"; //constructor function function__construct($text_in) { $this->body_text=$text_in; } function display() { print("<table border=1><tr><td>$this->body_text"); print("</td></tr></table>"); } } //creating an instance $box=new TextBox("custom text"); $box->display(); As the preceding code is executed, the output is an HTML table enclosing the text "custom text".
Recommended Posts
Please sign in to comment
You will be able to leave a comment after signing in
Sign In Now