Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP classes is it possible to create a private variable inside of a function?

In using PHP classes I have noticed that inside a class when I define a variable in a function as a property of that class in the $this->variablename way it automatically becomes a public variable of that class.

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

So that

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

Outputs: string

However, in the case that I wanted to create private variables only accessible to functions inside the class, is there anyway to declare them only inside of the setstring() function? Instead of declaring them as private outside of the function like this.

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

The reasons someone might do this are for neatness, so as not to have a long list of private variables declared at the beggining of a class.

like image 870
Maximilian Travis Avatar asked Apr 14 '17 17:04

Maximilian Travis


People also ask

How can use private variable in another class in PHP?

By using Public Method We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.

Can a class be private in PHP?

As of PHP 7.1. 0, class constants may be defined as public, private, or protected.

Can a class variable be private?

Class variables that are declared as private can not be referred to from other classes, they are only visible within their own class. It is considered better programming practice to use private rather than public class variables, and you should aim to do this in the remainder of the course.

What is private variable in PHP?

PHP - Access Modifiers There are three access modifiers: public - the property or method can be accessed from everywhere. This is default. protected - the property or method can be accessed within the class and by classes derived from that class. private - the property or method can ONLY be accessed within the class.


2 Answers

No, there is not a way to do that.

In PHP, you typically declare all your class/instance properties above your functions in alphabetical order with self-documenting comments. This is the most "neat" and clear way to write classes. It is also recommended that you avoid public properties entirely, using getters and setters as needed.

The canonical coding style for PHP is defined in PSR-1 and PSR-2. I also recommend that you check out PHPDoc.

Keep in mind, variables declared within the scope of your class method will be private to that method. You only need a class property if you plan to access it from other methods.

<?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';
  }

}
like image 168
jchook Avatar answered Oct 14 '22 01:10

jchook


How to create private variables in a PHP Class using OOP (Object Oriented Programming).

The best way to declare a private variable in a PHP Class is to create them above the __Construction method, by convention you may start the variable with an underscore after the dollar sign (i.e $_private_variable) to let other programmers reading your codes know at sight that it is a private variable, brilliant!

Please declare all your variable in a class as private except the __getter and __setter which are always public, unless you have a reason not to do so.

Use the __setter (__set) function to set value(s) to your private variable inside a the class, and when the value is needed, use the __getter (__get) function to return the values.

To make sense of it, let' create a very small Class that could be use to create different type of Vehicles, this will give you and insight on how to properly create private variable, set values to it and return values from it, ready?

    <?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");
?>

The output of this code:

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
)

To do a live test or experiment with this code, see the demo, change name, create new vehicle(s) as pleased.

I hope this helps.

like image 30
Prince Adeyemi Avatar answered Oct 13 '22 23:10

Prince Adeyemi