написал функцию Код (Text): public function _get($string)//socialId { $result = null; if(isset($this->userInfo[$string])) { $result = $this->userInfo[$string]; } return $result; } при передаче параметра в функцию _get('socialId'), параметр приходит пустым. $this->userInfo['socialId'] существует, но функция пытается прочесть $this->userInfo[''] в чем я туплю? подскажите
да. типа того, иначе гетов слишком много у меня. но так почему то пустоту функция принимает, может я строку не правильно передаю?
это как бы намек на то что магические методы с двумя ундерскорами пишутся а в листинге один. я тут к сожалению гадать вынужден так как нет примера использования кода. но чуйка мне подсказывает что ожидается что-то типа $obj->socialId и тогда выполняется магический __get() который не переопределяется методом _get() потому что у них разные имена. с другой стороны упомянуто что вызывается что-то с чем-то но внутри не то но метода отладки я тут тоже не наблюдаю.
функция раньше была такой, и всё работало Код (Text): public function getSocialId() { $result = null; if (isset($this->userInfo['socialId'])) { $result = $this->userInfo['socialId']; } return $result; } вызывал её так: $auther->getSocialId(); сейчас функцию вызываю так: $auther->_get('socialId'); но в качестве аргумента приходит пустота, и я не знаю почему. userInfo это json по сути если бы даже функция выглядела так: Код (Text): public function _get($string)//socialId { $result = null; if($string != null)//условие не выполняется { $result = $string; } else { $result = 'что не так со строками?'; } return $result; } функция выполняется, но при любом аргументе возвращается "что не так со строками?". не проходит проверку не не нуль, если проверку убрать, то просто возвращается пустота
Код (PHP): <?php class ru_php_forum_52291 { public function _get($string)//socialId { $result = null; if($string != null)//условие не выполняется { $result = $string; } else { $result = 'что не так со строками?'; } return $result; } } $auther = new ru_php_forum_52291; var_dump($auther->_get('socialId')); Код (Text): $ php fake.php string(8) "socialId" у меня даже идей нет в какую сторону копать... может быть больше листингов поможет?
хорошо, сейчас правда немного переделал, но оба кода готов отправить Код (Text): <?php namespace SocialAuther\Adapter; abstract class AbstractAdapter implements AdapterInterface { protected $clientId = null; protected $clientSecret = null; protected $redirectUri = null; protected $provider = null; protected $socialFieldsMap = array(); protected $userInfo = null; protected $caption = null; protected $id = null; public function __construct($config) { if (!is_array($config)) throw new Exception\InvalidArgumentException ( __METHOD__ . ' expects an array with keys: `client_id`, `client_secret`, `redirect_uri`, `Caption`, `provider`, `id`' ); foreach (array('client_id', 'client_secret', 'redirect_uri', 'Caption', 'provider', 'id') as $param) { if (!array_key_exists($param, $config)) { throw new Exception\InvalidArgumentException ( __METHOD__ . ' expects an array with key: `' . $param . '`' ); } else { $property = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $param)))); $this->$property = $config[$param]; } } } private function SetUserInfo($config) { $this->userInfo = $config; } /** * Get user social id or null if it is not set * * @return string|null */ function __get($param)//сейчас переделал в такой вид, по примеру из интернета, теперь не знаю что она принимает, но возвращает подозрительную пустоту, раньше была такой public function _get($param);//но оба варианта не работают у меня { return (isset($this->userInfo[$param])) ? $this->userInfo[$param] : 'not set'; } public function getCaption() { return $this->caption; } /** * Get user email or null if it is not set * * @return string|null */ public function getEmail() { $result = null; if (isset($this->userInfo['email'])) { $result = $this->userInfo['email']; } return $result; } public function getSocialId($param) { $result = null; if (isset($this->userInfo['socialId'])) { $result = $this->userInfo['socialId']; } return $result; } /** * Get user name or null if it is not set * * @return string|null */ public function getName() { $result = null; if (isset($this->userInfo['name'])) { $result = $this->userInfo['name']; } return $result; } /** * Get user social page url or null if it is not set * @return string|null */ public function getSocialPage() { $result = null; if (isset($this->userInfo['socialPage'])) { $result = $this->userInfo['socialPage']; } return $result; } /** * Get url of user's avatar or null if it is not set * * @return string|null */ public function getAvatar() { $result = null; if (isset($this->userInfo['avatar'])) { $result = $this->userInfo['avatar']; } return $result; } /** * Get user sex or null if it is not set * * @return string|null */ public function getSex() { $result = null; if(isset($this->userInfo['sex'])) { $result = $this->userInfo['sex']; } return $result; } /** * Get user birthday in format dd.mm.YYYY or null if it is not set * * @return string|null */ public function getBirthday() { $result = null; if (isset($this->userInfo['birthday'])) { $result = date('d.m.Y', strtotime($this->userInfo[$this->socialFieldsMap['birthday']])); } return $result; } /** * Return name of auth provider * * @return string */ public function getProvider() { return $this->provider; } public function getProviderId() { return $this->id; } /** * Get authentication url * * @return string */ public function getAuthUrl() { $config = $this->prepareAuthParams(); return $result = $config['auth_url'] . '?' . urldecode(http_build_query($config['auth_params'])); } /** * Make post request and return result * * @param string $url * @param string $params * @param bool $parse * @return array|string */ protected function post($url, $params, $parse = true) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, urldecode(http_build_query($params))); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($curl); curl_close($curl); if ($parse) { $result = json_decode($result, true); } return $result; } /** * Make get request and return result * * @param $url * @param $params * @param bool $parse * @return mixed */ protected function get($url, $params, $parse = true) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url . '?' . urldecode(http_build_query($params))); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($curl); curl_close($curl); if ($parse) { $result = json_decode($result, true); } return $result; } } код вызова функции, тоже переделал чуть Код (Text): [code]<?php require_once 'lib/SocialAuther/autoload.php'; require_once 'config.inc.php'; $adapters = array(); foreach($mysqli->query("SELECT * FROM `Socials` WHERE `Exist`!=0") as $row) { $class = 'SocialAuther\Adapter\\' . ucfirst($row['provider']); $adapters[$row['provider']] = new $class($row); } if(isset($_GET['provider']) && array_key_exists($_GET['provider'], $adapters) && !isset($_SESSION['user'])) { $auther = new SocialAuther\SocialAuther($adapters[$_GET['provider']]); if($auther->authenticate()) { $result = $mysqli->query ( "SELECT * FROM `Accounts` WHERE `provider_id` = '{$auther->getProviderId()}' AND `social_id` = '{$auther->socialId}' LIMIT 1" );//сейчас вызывается так и тут $record = $result->fetch_assoc(); if(!$record) { $values = array ( $auther->getProviderId(), $auther->socialId,//сейчас вызывается так и тут раньше вызывал $auther->_get('socialId'), $auther->getName(), $auther->getEmail(), $auther->getSocialPage(), $auther->getSex(), date('Y-m-d', strtotime($auther->getBirthday())), $auther->getAvatar() ); $query = "INSERT INTO `Accounts` (`provider_id`, `social_id`, `name`, `email`, `social_page`, `sex`, `birthday`, `avatar`) VALUES ('"; $query .= implode("', '", $values) . "')"; $result = $mysqli->query($query); } else { $userFromDb = new stdClass(); $userFromDb->provider = $record['provider_id']; $userFromDb->socialId = $record['social_id']; $userFromDb->name = $record['name']; $userFromDb->email = $record['email']; $userFromDb->socialPage = $record['social_page']; $userFromDb->sex = $record['sex']; $userFromDb->birthday = date('m.d.Y', strtotime($record['birthday'])); $userFromDb->avatar = $record['avatar']; } $user = new stdClass(); $user->provider = $auther->getProvider(); $user->socialId = $auther->getSocialId(); $user->name = $auther->getName(); $user->email = $auther->getEmail(); $user->socialPage = $auther->getSocialPage(); $user->sex = $auther->getSex(); $user->birthday = $auther->getBirthday(); $user->avatar = $auther->getAvatar(); if (isset($userFromDb) && $userFromDb != $user) { $idToUpdate = $record['id']; $birthday = date('Y-m-d', strtotime($user->birthday)); mysql_query ( "UPDATE `users` SET " . "`social_id` = '{$user->socialId}', `name` = '{$user->name}', `email` = '{$user->email}', " . "`social_page` = '{$user->socialPage}', `sex` = '{$user->sex}', " . "`birthday` = '{$birthday}', `avatar` = '$user->avatar' " . "WHERE `id`='{$idToUpdate}'" ); } $_SESSION['user'] = $user; } header("location:index.php"); } ?> </html> [/code] новым способом она как оказалось даже не вызывается