I've got a private variable in my class
private $noms = array(
"HANNY",
"SYS",
"NALINE"
);
I want to access it from a static method:
public static function howManyNom($searchValue){
$ar = $this->noms;
foreach($ar as $key => $value) {
...
But as normal I cant retrieve it with $this because there's no instance on a static method.
What's the right syntax to get $noms inside my static function?
Bookmark this question. Show activity on this post. private $noms = array( "HANNY", "SYS", "NALINE" );
We cannot directly access the instance variables within a static method because a static method can only access static variables or static methods.
The usual solution is to use a static member function to access the private static variable. A static member function is like a static member variable in that you can invoke it without an object being involved. Regular member functions can only be applied to an object and have the hidden "this" parameter.
So it goes into a private static method that the non-private factory methods call. Visibility (private versus public) is different from class method (i.e. static) versus instance method (non-static). A private static method can be called from a public method - static or not - but not from outside the class.
Make this attribute static too!
private static $noms = array(
"HANNY",
"SYS",
"NALINE"
);
public static function howManyNom($searchValue){
$ar = self::$noms;
foreach($ar as $key => $value) {
To access the $noms array make it static, you do that like so:
private static $noms = array();
You then access that like so:
self::$noms['some key']
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With