简体   繁体   中英

How can I use a variable in a class for changing its value globally in PHP

How can I use a variable in a class, such as if I change the value of the variable from member function then its value will be changed globally . How can I do this?

i think you are searching for this:

class abcd {
public $value;
function __construct($value) {
    $this->value        = $value;
}
public function change ($change)
{
     $this->value = $change;
}

}
$new= new abcd (123);
print_r($new);
$new->change (546);
print_r($new);

first.php

<?php    
class first {    
    private $name;
    function __construct() {
        $this->name="name";
    }

    function  changeName(){
        $this->name="newName";
    }

    function getName()
    {
        return $this->name;
    }    
}    
?>

second.php

<?php
    include 'first.php';
    $firstObject=new first;
    echo $firstObject->getName().'<br>';
    $firstObject->changeName();
    echo $firstObject->getName();

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM