簡體   English   中英

php類繼承$ this-> ...是未定義的?

[英]php class inheritance $this->… is undefined?

編輯:解決了,我在Controller類中使用的是private而不是受保護的屬性。

嘗試從繼承的類中使用屬​​性時出現錯誤。 我的Controller類看起來像這樣。

<?php

namespace App\Controllers;

use Http\Request;
use Http\Response;
use App\Templates\Renderer;

class Controller{
    private $request;
    private $response;
    private $renderer;

    public function __construct(Request $request, Response $response, Renderer $renderer){
        $this->request = $request;
        $this->response = $response;
        $this->renderer = $renderer;
    }
}

我要擴展的Pages類看起來像這樣。

<?php

namespace App\Controllers;

use App\Models\Book;


class Pages extends Controller{

    public function index(){
        $book = new Book;
        $book->title = 'test';
        // $book->save();
        // echo 'Book created';
        $html = $this->renderer->render('index');
        $this->response->setContent($html);
    }
}

我收到的錯誤看起來像這樣

Undefined property: App\Controllers\Pages::$renderer

您應該將$renderer字段的可見性從private更改為protected

那是因為

  • 私有字段/功能只能從自己的類中訪問
  • 可以從任何地方訪問公共領域/功能
  • 可以從擴展當前類的所有類(包括父類)訪問受保護的字段/函數

http://php.net/manual/en/language.oop5.visibility.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM