Reputation: 1672
I am very new to OOP. And i've read that a derived class can access the public and protected members of base class.
A.php
<?php
namespace App\Http\Controllers;
class A extends Controller
{
public $x=5;
public function index()
{...}
}
and B.php
<?php
namespace App\Http\Controllers;
class B extends A
{
public function index()
{
print_r($x);
}
}
why is $x
not accessed from derived class?
I have this route:
Route::get('/B/index','B@index');
I got the error:
undefined variable x.
Upvotes: 1
Views: 246
Reputation: 109
Please change code as bellow. it will show result.
class A
{
public $x=5; //or protected $x=5;
public function index()
{
echo "A";
}
}
class B extends A
{
public function index()
{
echo $this->x;
}
}
$classB = new B();
$classB->index();
you can use :http://phptester.net/ to test online
I Hope help you
Upvotes: 3
Reputation: 26288
Make the following changes in your code:
class B extends A
{
public function get()
{
echo $this->x; // will echo the value in variable $x;
}
}
$obj = new B;
$obj->get();
Upvotes: 3