Php 如何在类中的不同函数之间使用$x变量? class A{ var $x = 10; function a(){ return $this->x; } function b(){ echo $this->x; } } $obj = new A(); echo $obj->a(); ?>

Php 如何在类中的不同函数之间使用$x变量? class A{ var $x = 10; function a(){ return $this->x; } function b(){ echo $this->x; } } $obj = new A(); echo $obj->a(); ?>,php,Php,我正在学习PHP,我有一个类,我想在其中跨多个函数共享一个变量,如下所示,但不幸的是,我得到的错误如下: <b>Parse error</b>: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION on line <b>5</b><br /> class A{ var $x = 10; function a(){ return $t

我正在学习PHP,我有一个类,我想在其中跨多个函数共享一个变量,如下所示,但不幸的是,我得到的错误如下:

<b>Parse error</b>:  syntax error, unexpected T_VARIABLE, expecting T_FUNCTION on line <b>5</b><br />
class A{

    var $x = 10;

    function a(){

        return $this->x;
    }

    function b(){

        echo $this->x;
    }

}
$obj = new A();
echo $obj->a();
?>
分析错误:语法错误,意外的T_变量,第5行需要T_函数
那么,我如何在一个类中的不同函数之间使用$x变量,如果是noob查询,那么很抱歉

class A{

    var $x = 10;

    function a(){

        return $this->x;
    }

    function b(){

        echo $this->x;
    }

}
$obj = new A();
echo $obj->a();
?>
代码如下:

<?php


class A{

$x = 10;

    function a(){
        global $x;
        echo $x;
    }



    function b(){
        global $x;
        echo $x;
    }

}

?>

要访问非静态成员的属性,可以将
$this
引用为类

$this->x
因此,对于您的代码:

class A{
    //clarity
    public $x = 10;

    public function a(){
       echo $this->x;
    }

    public function b(){

        echo $this->x;
    }
}

$class = new A;
echo $class->a(); //results in 10
echo $class->b(); //results in 10

用户$this要访问类变量,还可以在函数a()中使用return,因为在实例化类时会自动调用类约定函数(因为它被视为类a的构造函数-类和函数的名称相同)
class A{

    var $x = 10;

    function a(){

        return $this->x;
    }

    function b(){

        echo $this->x;
    }

}
$obj = new A();
echo $obj->a();
?>

您应该使用
$this
访问类中的此变量

$this->x
您的代码如下所示:

<?php
class A{

public $x = 10; // make the scope of variable as public

    function a(){
        return $this->x; // use this variable as "$this->x" to access everywhere in that class
    }

    function b(){
       return $this->x;
    }
}

/*
In order to access you can use
*/
$myClass = new A;
echo $myClass->a(); //the output will be 10
echo $myClass->b(); //the output will be 10
?>


您可以将其声明为
public$x=10
并且您可以在每个窗口中访问
$this->x
method@Sundar如果我使用public,那么$x变量对任何类都是可见的,对吗?所以使用变量$x作为“Private”是正确的,对吗?如果你不想通过调用外部的对象访问,你可以将它声明为
Private
如果我使用public,那么$x变量对任何类都是可见的,对吗?所以使用变量$x作为“Private”是正确的,对吗?Public-任何类都可以使用它。私有-只有这个类可以使用它。受保护-实现该类的任何类都可以使用它。取决于您的需要。请您给出您的答案,并解释为什么此代码会回答此问题?代码唯一的答案是,因为他们不教解决方案。