Привет всем! У меня возникла проблема с объявлением "магического" метода __construct() в классе. Реализую MVC паттерн для своего сайта. С объявлением других методов нет никаких проблем, а вот именно с "магическими" сразу возникает ошибка такого рода: (Warning: Missing argument 1 for mTranslate::__construct(), called in A:\home\test2.ru\www\index.php on line 1048 ). Смотрим что у нас в индексном файле на строке 1048 Код (Text): $_o = new $_sModelName(); . Вот впринципе полный код скрипта, который отвечает за загрузку скриптов моделей из папки _models: Код (Text): class Looking_Model extends Looking { /** * Loads a model script to be executed and to return an object variable. * * Note all variables use underscores so as not to pass them to the model class file. This is * just a precautionary failsafe. We do an unset() on all variables we can before the * require_once() call. * * @param string $_sModelName The model path, such as 'Test', or 'SampleSystem/Test'. This translates * to app/_models/Test.php and app/_models/SampleSystem/Test.php, for example. Note that models do not have * an 'm' prefix before the filename because we really only needed in tabbed text editors to delineate * files which are controllers or views, which is why controllers have the "c" prefix, while views * have the "v" prefix. */ public function load($_sModelName) { $_F = $this->core->base(); if (strpos(' ' . $_sModelName,'/')>0) { $_sBaseName = basename($_sModelName); $_sPath = dirname($_sModelName); $_sPath = rtrim($_sPath, '/') . '/'; $_sModelPath = $_sPath . $_sBaseName . '.php'; $_sModelName = basename($_sModelName); } else { $_sModelPath = $_sModelName . '.php'; } if (!file_exists($_F . '/app/_models')) { trigger_error('Your folder layout is missing a app/_models folder',E_USER_ERROR); } $_sPath = $_F . '/app/_models/' . $_sModelPath; if (!file_exists($_sPath)) { trigger_error('Your folder layout is missing a "' . $_sPath . '" models file',E_USER_ERROR); } unset($_sBaseName); unset($_sModelPath); unset($_F); require_once($_sPath); $_o = new $_sModelName();// строка 1048, которая выдает ошибку. $_o->core = $this->core; $_o->request = $this->request; $_o->model = $this; $_o->view = $this->view; $_o->data = $this->data; return $_o; } } Вот как автор объясняет зачем перед всеми переменными он использует нижнее подчеркивание: "* Note all variables use underscores so as not to pass them to the model class file. This is just a precautionary failsafe." Я пробовал убирать все подчеркивания - ошибка не ушла.
Это что значит? Что я не передал что-то или где-то ошибка? Вот код самого класса: Код (Text): class mTranslate extends Looking { /** * A sample class method * * @param string $sParam1 Something to query the names table's first names by. * @return string The first matching name. */ private $phrases; public function __construct($site_lang) { $this->phrases = array(); $PDO = $this->data->mysql(); $sSQL = "select * from translation where lang_id = :site_lang"; $st = $PDO->prepare($sSQL); // Подготавливает запрос к выполнению и возвращает ассоциированный с этим запросом объект $st->bindParam(':site_lang', $site_lang, PDO::PARAM_STR); $st->execute(); $rsRows = $st->fetchAll(); foreach($rsRows as $rwRow) { $this->phrases[strtolower($rwRow->phrase)] = $rwRow->translation; } } public function translate($phrase) { $phrase = strtolower($phrase); if (isset($this->phrases[$phrase])) { return $this->phrases[$phrase]; } else { return "###"; } } } // end class
Хорошо. Тогда вопрос : почему в классах где я не использую конструктор и передаю аргументы, такой ошибки нет?
Я не знаю, что в других случаях. Тут вот ругается, что аргумента не передал. А он есть, и без дефолтного значения. Значит он требуется.
Разрабатывайте даже простые проекты в IDE-среде господа и будет вам счастье. Даже до запуска приложения покажет большинство ошибок.