name; class "/>

Implicit Property Declaration

Defining a property implicitly

<?php
$object1 = new User();
$object1->name = "Alice";
echo $object1->name;
class User {}
?>

This code correctly outputs the string “Alice” without a problem, because PHP implicitly declares the variable $object1->name for you. But this kind of programming can lead to bugs that are infuriatingly difficult to discover, because name was declared from outside the class.
To help yourself and anyone else who will maintain your code, get into the habit of always declaring your properties explicitly within classes. Also, when you declare a property within a class, you may assign a default value to it. The value you use must be a constant and not the result of a function or expression.

Valid and invalid property declarations

<?php
class Test
{
public $name = "Paul Smith"; // Valid
public $age = 42; // Valid
public $time = time(); // Invalid - calls a function
public $score = $level * 2; // Invalid - uses an expression
}
?>


Related Topic JSP Scriptlets Tag for Variable Expressions and Statements Declaration
Difference between DispatchAction and LookupDispatchAction?
What is difference between LookupDispatchAction and DispatchAction in Struts
Servlet Interview Questions & Answers
What is OSI Model and its Layers in Communication System

nScraps.com © 2011   Privacy Policy  Terms of Service  Feedback