0

With a static property or function I don't need to make a new instance, then, can I read a static variable out of the class? In my exemplo, the variable do not return any value.

<?php //person.class.php

    Class Person{

        static $name;

        static function setName($new_name){

            self::$name = $new_name;

        }

    }

?>
     <html> <!--index.html-->
        <form action="add_name.php" method="post">

            <input type="text" name="name"></input>
            <input type="submit">
        
        </form>
    </html>
<?php //add_name.php

    require("person.class.php");

    $name = $_POST["name"];

    Person::setName($name);

    echo(Person::$name." now is on static property name. <a href='show.php'>See the name</a>");

?>
<?php //show.php

    require("person.class.php");

    echo("The name is:".Person::$name); //return empty :(

?>

I send a value to a static property on class person and I call the static property on show.php and the result is empty.

  • Why is `name` a static property? Shouldn't every person have a different name? – Barmar Nov 10 '22 at 23:28
  • How are `add_name.php` and `show.php` related? Are they included together in the same request? PHP is essentially stateless (ignoring any persistence layers like `$_SESSION`) so a static property set in one request won't exist in a second one – Phil Nov 10 '22 at 23:28
  • 1
    Nothing in PHP persists between requests beyond session data, and whatever else you've explicitly persisted in a database, files, etc. Setting a class property is not one of these, static or otherwise. – Sammitch Nov 10 '22 at 23:29
  • You can also use session variables, but then you'll need to create an instance. See https://stackoverflow.com/questions/5578679/how-can-i-store-object-class-into-a-session-in-php But this won't keep static properties. – Barmar Nov 10 '22 at 23:31
  • It's worth noting that static properties generally boil down to "namespacing for global state" and have pretty much all the same drawbacks as global state, minus namespacing. Also, as Barmar has already noted, you're basically declaring that all people have the same name. – Sammitch Nov 10 '22 at 23:37

0 Answers0