In PHP classes is it possible to create a private variable inside of a function? -
in using php classes have noticed inside class when define variable in function property of class in '$this->variablename way' automatically becomes public variable of class.
class example { public function setstring(){ $this->string = "string"; } }
so
$class = new example(); echo $class->string;
outputs: string;
however in case wanted create private variables accessible functions inside class, there anyway declare them inside of function setstring()? instead of declaring them private outside of function this.
class example { private $string =''; public function setstring(){ $this->string = "string"; } }
the reasons might neatness, not have long list of private variables declared @ beggining of class.
no, there not way that.
in php, typically declare all class/instance properties above functions in alphabetical order self-documenting comments. "neat" , clear way write classes. recommended avoid public properties entirely, using getters , setters needed.
the canonical coding style php defined in psr-1 , psr-2. recommend check out phpdoc.
keep in mind, variables declared within scope of class method private method. need class property if plan access other methods.
<?php class example { /** * holds private string * @var string */ private $string = ''; /** * sets private string variable */ public function setstring() { $this->string = 'this string accessible other methods'; $privatevar = 'this string accessible within method'; } }
Comments
Post a Comment