如何声明“子对象”在 PHP 中
我对 PHP 中的 OOP 比较陌生,我不确定我想做的事情是否可行或推荐。无论如何,我都想不通。是否有任何可能有帮助的教程或文档?
我有一个系统,其中每个用户都有多个“库”。每个库都包含许多“元素”。
DB 设置如下:
user_libraries
- id (unique)
- user_id (identifies user)
- name (just a string)
elements
- id (unique)
- content (a string)
library_elements
- id (unique)
- library_id
- element_id
其中 library_id
是来自 user_libraries
的 id,element_id
是来自 elements
的 id。
我希望能够访问给定用户的库及其元素。
我已经设置了库类,并且可以使用它来检索库列表(或子列表)。
我这样做是这样的:
$mylibraryset = new LibrarySet();
$mylibraryset->getMyLibraries();
给出(当我使用 print_r 时):
LibrarySetObject (
[user_id] => 105
[data_array] => Array (
[0] => Array (
[id] => 1
[user_id] => 105
[type] => 1
[name] => My Text Library
)
[1] => Array (
[id] => 2
[user_id] => 105
[type] => 2
[name] => Quotes
)
)
)
现在,我希望能够为每个库(data_array 中的元素)检索所有元素。
到目前为止,我最好的想法是执行以下操作:
foreach($mylibrary->data_array as $library) {
$sublibrary = new Library();
$sublibrary -> getAllElements();
}
其中 Sublibrary 是另一个具有 getAllElements 函数的类。但我还不能完全让它工作,而且我不确定我是否走对了路......
有没有一种方法可以让我最终能够执行如下操作,以检索特定的元素?
$mylibrary->sublibraries[0]->element[0]
I'm relatively new to OOP in PHP, and I'm not sure if what I'm trying to do is possible or recommended. In any case, I can't figure it out. Are there any tutorials or documentation which might help?
I have a system in which each user has a number of 'Libraries'. Each Library contains a number of 'Elements'.
DB set up is as follows:
user_libraries
- id (unique)
- user_id (identifies user)
- name (just a string)
elements
- id (unique)
- content (a string)
library_elements
- id (unique)
- library_id
- element_id
where library_id
is the id from user_libraries
, and element_id
is that from elements
.
I want to be able to access a given user's library, and their elements.
I've set up the library class, and can use it to retrieve the list of libraries (or a sub-list).
I do this like this:
$mylibraryset = new LibrarySet();
$mylibraryset->getMyLibraries();
which gives (when I use print_r):
LibrarySetObject (
[user_id] => 105
[data_array] => Array (
[0] => Array (
[id] => 1
[user_id] => 105
[type] => 1
[name] => My Text Library
)
[1] => Array (
[id] => 2
[user_id] => 105
[type] => 2
[name] => Quotes
)
)
)
Now, what I'd like to be able to do is for each of those libraries (the elements in data_array), to retrieve all the elements.
The best idea I've had so far is to do something like:
foreach($mylibrary->data_array as $library) {
$sublibrary = new Library();
$sublibrary -> getAllElements();
}
where Sublibrary is another class which has the function getAllElements
. I can't quite get it to work though, and I'm not sure I'm on the right lines...
Is there a way that I can then end up being able to do something like the following, to retrieve a specific element?
$mylibrary->sublibraries[0]->element[0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)