完整的方法贴在下面。调用 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 参数被翻译成以下内容:
返回新的 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);
}