What is "Static" for and how?

Asked

Viewed 713 times

1

I am very doubtful about how to use the "Static" in an attribute , if someone can get me that doubt I would really appreciate, thank you.

  • Static in a class or function? has difference

  • methods and attributes

1 answer

1

Keyword 'Static'

Declaring members or methods of a class as static makes them accessible without having to instantiate the class. A member declared static cannot be accessed with an instantiated class object (although static methods can).

Exemplo #1 Exemplo de membro estático

<?php
class Foo
{
    public static $meu_estatico = 'foo';

    public function valorEstatico() {
        return self::$meu_estatico;
    }
}


class Bar extends Foo
{
    public function fooEstatico() {
        return parent::$meu_estatico;
    }
}


print Foo::$meu_estatico . "\n";

$foo = new Foo();
print $foo->valorEstatico() . "\n";
print $foo->$meu_estatico . "\n";      // "Propriedade" Indefinida $meu_estatico

print $foo::$meu_estatico . "\n";
$classname = 'Foo';
print $classname::$meu_estatico . "\n"; // No PHP 5.3.0

print Bar::$meu_estatico . "\n";
$bar = new Bar();
print $bar->fooEstatico() . "\n";
?>

Reference: http://php.net/manual/en/language.oop5.static.php

  • Thank you very much, I was able to understand better with your example, thank you very much !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.