访问和返回函数中的私有属性

时间:2020-08-01 17:35:16

标签: php

我观看了this有关PHP的教程,在他的视频中,他将属性设置为private,这意味着我们无法在class之外访问它。但是,当他创建返回该private属性的函数时,他就能echo该属性。

它对他有用,只是不打印任何东西

<?php
        class Book {
            private $rating;
            public $title;

            function __construct($title, $rating) {
                $this -> title = $title;
                $this -> rate = $rate;
            } 
            
            function getRating() {
                return $this -> rating;
            }
        }
        $book1 = new Book('Harry Potter', 'PG-13'); // object instance
        echo $book1 -> getRating(); // Does not print anything
?>

更新

我改变了

$this -> rate = $rate;

收件人

$this -> rate = $rating;

但是它仍然不能打印任何东西

2 个答案:

答案 0 :(得分:1)

在构造函数__construct中,您应该执行以下操作:

$this -> rating = $rating;

否:

$this -> rate = $rate;

答案 1 :(得分:0)

欢迎使用StackOverflow。

您从哪里获得 $ rate 变量?它基本上无处使用。如果出现$ rating,并且$ this-> rating是全局变量,则没有$ rate变量。

$this->title等之间也没有空格。

代码:

<?php
    
    // Use this function to make sure your error handling is tightest:
    error_reporting(E_ALL);
    
    // Start a new class
    class Book {
        
        // We are setting the rating to be private:
        private $rating;
        
        // And we are setting the title to be public: You could also use 'var' here instead:
        var $title;
        
        // This is the function behind new Book () .. it is a construction function.
        function __construct ($title, $rating) {
            
            // You have $title coming and you are setting the classes global variable to it as well:
            $this->title = $title;
            
            // Same as above, but this is private, so outside of this class you cant access it:
            $this->rating = $rating;
        } 
        
        // This the function to get the rating:
        function getRating () {
            
            // This is the variable from the 5th line now. It is in fact private, but since the
            // function is inside the class, then this function getRating is allowed to access the variable
            // there for it will print it out without problems:
            return $this->rating;
        }
    }
    
    // Init the class and insert some basic information:
    $book1 = new Book('Harry Potter', 'PG-13');
    
    // Will print out 'PG-13'
    echo $book1->getRating() . '<br>';
    
    // Title will show up, as it is public:
    echo $book1->title . '<br>';
    
    // But accessing the rating directly, will not show anything:
    echo $book1->rating . '<br>';
    
    // Since the rating is private, then it will ultimate throw an error,
    // so this will kill the script or show the error, depending on your hosting settings:
    echo 'This probably wount show up';
    // yup, it gives you:
    // Fatal error: Uncaught Error: Cannot access private property Book::$rating in [.........]
?>

输出:
enter image description here

希望这有助于您进一步了解更多PHP。