简体   繁体   中英

how to use a variable in another variable in a php class

How I can use a variable in another variable in a php class like this:

<?php

class example
{
    var $first_num = 8;
    var $second_num = $first_num + 3;
    public function forexample($num)
    {
            if($num == $this->first_num)
            {
                    echo $this->second_num;
            }

    }
    etc...
}

?>

I want use this way in a class. please help me.

What you want to do is actually this:

<?php
class example
{
    var $first_num;
    var $second_num;

    function __construct() {
        $this->first_num = 8;
        $this->second_num = $this->first_num + 3;
    }
}

Remember that while you can initialize variables directly while declarating them in the class body, you might want to use the class constructor for more complicated initializations.

In this specific case, it is forbidden to declare a variable using a non-constant value, so the use of the constructor is mandatory for the variable $second_num .

Also, if you want to fine-tune variable visibility, you might want to use the private , public , or protected access modifiers instead of the legacy var , which is deprecated.

You will have to do this in the constructor. See http://php.net/manual/en/language.oop5.properties.php :

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See SirDarius's answer.

You have to utilize the constructor. Once you do that, you can use the variables anywhere in the class!

<?php
    class example {

        private $first_num;
        private $second_num;

        function __construct() {
            $this->first_num = 8;
            $this->second_num = $this->first_num + 3;
        }


    }
?>

Since you updated your question, you will have to set your variables to public not private.

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