在PHP类中,是否可以在函数内部创建私有变量?

时间:2017-04-14 17:33:09

标签: php function class scope

在使用PHP类时,我注意到在类中,当我以$this->variablename方式将函数中的变量定义为该类的属性时,它会自动成为该类的公共变量。

class example {
    public function setstring() {
        $this->string = "string";
    }
}

那样

$class = new example();
echo $class->string; 

输出:string

但是,如果我想创建只能访问类中函数的私有变量,那么无论如何只能在setstring()函数内部声明它们吗?而不是像这样在函数之外将它们声明为私有。

class example {
    private $string ='';
    public function setstring() {
        $this->string = "string";
    }
}

有人可能会这样做的原因是为了整洁,以免在课程开始时声明一长串私有变量。

3 个答案:

答案 0 :(得分:6)

,没有办法做到这一点。

在PHP中,您通常使用自记录注释按字母顺序在函数上方声明所有您的类/实例属性。这是最好的"整洁"并且清楚地写课程。还建议您根据需要使用getter和setter完全避免使用公共属性。

PHP的规范编码样式在PSR-1PSR-2中定义。我还建议您查看PHPDoc

请记住,在类方法范围内声明的变量将是该方法的私有变量。如果您打算从其他方法访问它,则只需要一个类属性。

<?php
class Example {

  /**
   * Holds a private string
   * @var string
   */
  private $string = '';

  /**
   * Sets the private string variable
   */
  public function setString() {
    $this->string = 'This string is accessible by other methods';
    $privateVar = 'This string is only accessible from within this method';
  }

}

答案 1 :(得分:1)

这不是一种语言功能,但是有一个非常简单有效的技巧:

class Test
{
    /**
     * Hidden dynamic data.
     * @var object
     */
    private $_ = (object)[];

    public function setString()
    {
        $this->_->string = "string";
    }
}

您可以将$_更改为所需的内容,但对我来说,它看起来确实比较笨拙。 $this->this也是一个选项。

答案 2 :(得分:0)

  

如何使用OOP在PHP类中创建私有变量   (面向对象编程)。

在PHP类中声明私有变量的最佳方法是在__Construction方法上方创建它们,按照惯例,您可以在美元符号(即$ _private_variable)后用下划线开头该变量,以让其他程序员阅读您的代码看到它是一个私有变量 brilliant

请在您的类中将所有变量声明为私有变量,但__getter和__setter始终为公共变量,除非您有理由不这样做。

使用__setter(__set)函数将值设置为类中的私有变量,然后在需要该值时,使用__getter(__get)函数返回值。

为了理解这一点,让我们创建一个很小的类,该类可以用于创建不同类型的Vehicle,这将使您了解如何正确创建私有变量,为其设置值并从中返回值准备好了吗?

    <?php

    Class Vehicle{

        /* Delcaration of private variables */

        private $_name = "Default Vehicle";
        private $_model;
        private $_type;
        private $_identification;

        /* Declaration of private arrays */
        private $_mode = array();
        private $feature = array();

        /* Magic code entry function, think of it as a main() in C/C++ */
        public function __construct( $name, $model, $type ){
            $this->create_vehicle( $name, $model, $type );
        }

        /* __getter function */
        public function __get( $variable ){
            if( !empty($this->$variable) ){
                $get_variable = $this->$variable;
            }

            return $get_variable;
        }

        /* __setter function */
        public function __set( $variable, $target ){
            $this->$variable = $target;
        }

        /* Private function */
        private function create_vehicle( $name, $model, $type ){
            $this->__set( "_name", $name );
            $this->__set( "_model", $model);
            $this->__set( "_type", $type );
        }

    }

    //end of the class.

?>

<?php
    /* Using the Vehicle class to create a vehicle by passing
       three parameters 'vehicle name', 'vehicle model', 'vehicle type' 
       to the class.
    */

    $toyota = new Vehicle("Toyotal 101", "TY101", "Sedan");

    /* Get the name and store it in a variable for later use */
    $vehicle_name = $toyota->__get('_name');

    /* Set the vehicle mode or status */
    $vehicle_mode = array(
            'gas' => 50,
            'ignition' => 'OFF',
            'tire' => "OK",
            'year' => 2020,
            'mfg' => 'Toyoda',
            'condition' => 'New'
        );

    /* Create vehicle features */    
    $vehicle_feature = array(
            "Tire" => 4,
            "Horse Power" => "V6",
            "blah blah" => "foo",
            "Airbag" => 2,
            "Transmission" => "Automatic"
            //....
        );

    /* Create vehicle identification */
    $vehicle_identification = array(
        "VIN" => "0001234567ABCD89",
        "NAME" => $vehicle_name,
        "FEATURE" => $vehicle_feature,
        "MODEL" => $vehicle_mode,
        "YEAR" => 2020,
        "MFG" => "Totota"
    ); 


    /* Set vehicle identification */
    $toyota->__set("_identification", $vehicle_identification );

    /* Set vehicle features */
    $toyota->__set("_feature", $vehicle_feature );

    /* Set vehicle mode */
    $toyota->__set("_mode", $vehicle_mode);

    /* Retrieve information and store them in variable using __get (getter) */
    $vehicle_name = $toyota->__get('_name');
    $vehicle_mode = $toyota->__get('_mode');
    $vehicle_id =  $toyota->__get('_identification');
    $vehicle_features = $toyota->__get('_feature');
    $vehicle_type = $toyota->__get('_type');
    $vehicle_model = $toyota->__get('_model');


    /* Printing information using store values in the variables. */
    echo "Printing Vehicle Information\n";
    echo "*****************************\n";

    echo "Vehicle name is $vehicle_name \n";
    echo "Vehicle Model is $vehicle_model \n";
    echo "Vehich type is $vehicle_type \n";

    printf("\n\n");
    echo "Printing Vehicle Mode\n";
    echo "***********************\n";
    print_r( $vehicle_mode );

    printf("\n\n");
    echo "Printing Vehicle Features\n";
    echo "**************************\n";
    print_r( $vehicle_features );

    printf("\n\n");

    echo "Printing Vehicle Identification\n";
    echo "******************************\n";
    print_r( $vehicle_id );


    printf("\n\n");
?>

此代码的输出:

Printing Vehicle Information
*****************************
Vehicle name is Toyotal 101 
Vehicle Model is TY101 
Vehich type is Sedan 


Printing Vehicle Mode
***********************
Array
(
    [gas] => 50
    [ignition] => OFF
    [tire] => OK
    [year] => 2020
    [mfg] => Toyoda
    [condition] => New
)


Printing Vehicle Features
**************************
Array
(
    [Tire] => 4
    [Horse Power] => V6
    [blah blah] => foo
    [Airbag] => 2
    [Transmission] => Automatic
)


Printing Vehicle Identification
******************************
Array
(
    [VIN] => 0001234567ABCD89
    [NAME] => Toyotal 101
    [FEATURE] => Array
        (
            [Tire] => 4
            [Horse Power] => V6
            [blah blah] => foo
            [Airbag] => 2
            [Transmission] => Automatic
        )

    [MODEL] => Array
        (
            [gas] => 50
            [ignition] => OFF
            [tire] => OK
            [year] => 2020
            [mfg] => Toyoda
            [condition] => New
        )

    [YEAR] => 2020
    [MFG] => Totota
)

要对此代码进行实时测试或实验,请参见demo,更名,并根据需要创建新的车辆。

我希望这会有所帮助。