我对joomla core和PHP知之甚少。为了更好地处理我的网站,我试图阅读joomla核心的一小部分,当我遇到这个函数JTable:getInstance
, (libraries 'joomla'table'table.php line268),它返回
return new $tableClass($db);
要了解什么getInstance
返回,我需要知道这个$tableClass
是如何定义的,所以我在我的网站的所有php文件中搜索它,虽然有很多参考资料,甚至一些所谓的"定义",正如本页所指出的,它们都不是我要找的。我期待类似
class tableClass{...}
此外,在其他php文件中,有这些行:
$row = JTable::getInstance('K2Item', 'Table');
$row->hit($id);
所以在我看来,getInstance
返回的应该是一个具有成员hit()
的对象,所以我期待类似
class tableClass{...
function hit(){
.....
}
}
但是这种代码无处可寻,所以我被困在这里,绝对需要帮助。
我的一些想法:$tableClass真的是一个类吗?我注意到它有一个$
,这是所有其他类没有?如果它不是一个类,那么为什么它可以像这样调用new $tableClass
?我真的需要了解这些基础知识,但它是有点难谷歌关键词$
。
完整方法粘贴在下面。当调用JTable::getInstance时,必须传递$type作为参数。getInstance方法然后使用$type来定义$tableClass,如下所示。
// Sanitize and prepare the table class name.
$type = preg_replace('/[^A-Z0-9_'.-]/i', '', $type);
$tableClass = $prefix . ucfirst($type);
如果这个类还不存在,那么方法将继续加载(导入)这个类,最后调用return new $tableClass($db);
所以$tableClass只是一个基于$type参数的动态变量。
在上面的例子中:
$row = JTable::getInstance('K2Item', 'Table');
$type和$prefix参数被翻译成如下格式:
return new TableK2Item($db);
如果你搜索TableK2Item你确实应该找到有hit()方法的类
所以$tableClass实际上是在getInstance方法中定义的。
这有意义吗?
/**
* Static method to get an instance of a JTable class if it can be found in
* the table include paths. To add include paths for searching for JTable
* classes see JTable::addIncludePath().
*
* @param string $type The type (name) of the JTable class to get an instance of.
* @param string $prefix An optional prefix for the table class name.
* @param array $config An optional array of configuration values for the JTable object.
*
* @return mixed A JTable object if found or boolean false if one could not be found.
*
* @link https://docs.joomla.org/JTable/getInstance
* @since 11.1
*/
public static function getInstance($type, $prefix = 'JTable', $config = array())
{
// Sanitize and prepare the table class name.
$type = preg_replace('/[^A-Z0-9_'.-]/i', '', $type);
$tableClass = $prefix . ucfirst($type);
// Only try to load the class if it doesn't already exist.
if (!class_exists($tableClass))
{
// Search for the class file in the JTable include paths.
jimport('joomla.filesystem.path');
$paths = self::addIncludePath();
$pathIndex = 0;
while (!class_exists($tableClass) && $pathIndex < count($paths))
{
if ($tryThis = JPath::find($paths[$pathIndex++], strtolower($type) . '.php'))
{
// Import the class file.
include_once $tryThis;
}
}
if (!class_exists($tableClass))
{
// If we were unable to find the class file in the JTable include paths, raise a warning and return false.
JLog::add(JText::sprintf('JLIB_DATABASE_ERROR_NOT_SUPPORTED_FILE_NOT_FOUND', $type), JLog::WARNING, 'jerror');
return false;
}
}
// If a database object was passed in the configuration array use it, otherwise get the global one from JFactory.
$db = isset($config['dbo']) ? $config['dbo'] : JFactory::getDbo();
// Instantiate a new table class and return it.
return new $tableClass($db);
}