Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current class name/object inside PowerShell static class method?

I need $this to work inside static class! How to achieve that? Any workaround? I have analyzed return of Get-PSCallStack in class context and found nothing useful.

I need this for (a) logging and for (b) calling other static methods of same class without mentioning its name again and again.

Sample code (PowerShell v5):

class foo {
    static [void]DoSomething() {
        [foo]::DoAnything()  #works

        #$this.DoAnything   #not working

        $static_this = [foo]
        $static_this::DoAnything() #works

    }
    static [void]DoAnything() {
        echo "Done"
    }
}

[foo]::DoSomething()
like image 572
Anton Krouglov Avatar asked Aug 20 '16 15:08

Anton Krouglov


1 Answers

Static classes do not have this pointer. See MSDN

Static member functions, because they exist at the class level and not as part of an object, do not have a this pointer. It is an error to refer to this in a static method.

You must call method by class name.

like image 82
Paweł Dyl Avatar answered Sep 29 '22 17:09

Paweł Dyl