SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
Thread: oops question
-
Oct 17, 2007, 20:48 #1
- Join Date
- Jul 2007
- Posts
- 27
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
oops question
Hi there friends
am kind of new to oops, and i have a question.
Lest say i have a class a, class b extends a, class c extends b..
how can i have access to a property in class a in class b?i tried defining it as public, but it did'nt work for me, any suggestions?
Thanks
Vru
-
Oct 17, 2007, 22:13 #2
- Join Date
- Jan 2002
- Location
- Australia
- Posts
- 2,634
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Because b extends a it can access a's properties though they were it's own.
i.e
PHP Code:class B
{
public function someMethod() {
return $this->propert_defined_in_a;
}
}
You can have your class B constructor call the parent constructor if necessary.
If class B has no constructor defined then the class A constructor will run automatically.
PHP Code:class B
{
public function __construct() {
parent::__construct();
}
}
-
Oct 18, 2007, 01:16 #3
- Join Date
- Jul 2007
- Posts
- 27
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Okay, looks like i got the picture, but what do i need to do if i need class c to be able to acess properties of class?
-
Oct 18, 2007, 05:06 #4
- Join Date
- Jan 2002
- Location
- Australia
- Posts
- 2,634
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
It's best not to inherit too deeply because it can get confusing. A better idea is probably to compose or aggregate a new class within the class that needs to use it.
E.g passing one object to another (data access example)
The constructor of the "articles" class receives a reference to the dataAccess object as an argument to the constructor
PHP Code:class articles
{
private $dataAccess; //object
public function __construct($dataAccess) {
$this->dataAccess = $dataAccess;
}
public function get_recent($limit = 5) {
$query = "SELECT title FROM `articles` ORDER BY date DESC LIMIT " . (int) $limit;
return $this->dataAccess->get($query);
}
}
//Calling Code
require('dataAccess.php');
$data = new dataAccess();
$articles = new articles($data);
print_r($articles->get_recent(6));
PHP Code:class users
{
private $dataAccess;
public function __construct() {
require_once('dataAccess.php');
$this->dataAccess = new dataAccess();
}
public function create_user($username, $password) {
$query = "INSERT INTO `users` (username, password) VALUES ($username, $password");
return $this->dataAccess->insert($query));
}
}
-
Oct 18, 2007, 19:15 #5
- Join Date
- Jul 2007
- Posts
- 27
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Exactly what i was looking for, i have a data access variable in class a and i want it to be available across class b and class c as well, the given example sounds like it could solve my problem.
Thanks
Bookmarks