Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private variable from static function in php

Tags:

php

static

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?

like image 806
Michele Avatar asked Aug 10 '12 11:08

Michele


People also ask

How can access private variable in static method in PHP?

Bookmark this question. Show activity on this post. private $noms = array( "HANNY", "SYS", "NALINE" );

Can static methods access private variables?

We cannot directly access the instance variables within a static method because a static method can only access static variables or static methods.

How do you access private static members?

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.

Can static method be private PHP?

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.


2 Answers

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) {
like image 102
tuxtimo Avatar answered Oct 08 '22 12:10

tuxtimo


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'];

like image 31
martynthewolf Avatar answered Oct 08 '22 12:10

martynthewolf