Вопросы по ООП в PHP

8.11K
.
То есть если класс addClassid является абстрактным классом то его экземпляр с помощью конструктора класса создать невозможно. Но я читал, что его (абстрактный класс) можно подобно простой переменной можно указать как аргумент функции. Так вот, меня интересует, как именно это можно сделать ведь конструктора то в нём нет?...
.
Ja_Kazanova (27.08.2012/14:27)
Я как бы начал учить ООП и все ничего, и все понятно кроме... ПОЛИМОРФИЗМма
Если на просторах этого сайта имеются спецы которые могли бы мне нормальным человеческим языком обьяснить его идею, принци
Тут не нужно быть спецом, достаточно заглянуть хотябы в туже википедию.
Полиморфизм - один интерфейс, множество реализаций.
Например:

// Интерфейс для предоставления доступа к каким либо данным
abstract class Storage {

  abstract function get();
  abstract function set();

}

// Реализация для какого либо конфига
class Conf extends Storage {

  function get() {
    return file_get_contents('config');
  }

  function set($conf, $data) {
    return file_put_contents($conf, $data);
  }

}

// Реализация для MySQL
class Db extends Storage {

  function get() {
    return mysql_fetch_assoc(mysql_query("SELECT FROM `table` WHERE `item` = '1'"));
  }
  
  function set($data) { 
    mysql_query("UPDATE `table` SET `text` = '" . mysql_real_escape_string($data) . "' WHERE `item` = '1'");
  }

}

Хотя в данном примере можно было бы использовать и сам интерфейс вместо абстрактного класса
.
Ja_Kazanova, Вот еще один пример, надеюсь теперь станет ясно почему так
error_reporting(-1);
abstract class Display
{
	public function display()
	{
	  echo "<pre>" . get_class($this) . "</pre>";
	}
}

class OneDisplay extends Display
{
	public function display()
	{
		echo  "<pre>" . get_class($this) . "</pre>";
	}
}

class TwoDisplay extends Display {
	public function display()
	{
		echo  "<pre>" . get_class($this) .  "</pre>";
	}
}

function display(Display $d)
{
	$d->display();
}

$one = new OneDisplay;
$two = new TwoDisplay;
//$d = new Display; // Вызовет ошибку
display($one);
display($two);

/*
На экране появится следующее:
OneDisplay
TwoDisplay
OneDisplay
TwoDisplay
*/
.
Забыл добавить, еще нужно к echo в методах добавить __CLASS__ Для полной картины
.
Подскажите пожалуйста для чего нужны конструкции try {} catch() {} и исключения (trow new Exeption). Вот ломаю голову где это можно применить и для чего.
.
Screamer
~XeOn~, Для обработки ошибок
На словах я плохо объясняю лучше как обычно пример оставлю:
class Db extends mysqli
{

    /**
     * Construct
     *
     * Get connection parameters. Connect to mysql server. Setup connection charset
     * Description of connection parameters:
     * [host]     (string) hostname
     * [user]     (string) username
     * [password] (string) password
     * [db]       (string) database
     * [charset]  (string) charset
     *
     * @param (object) $conf Connection parameters
     * @throws Base_Exception If connection failed
     * @return (void)
     */
    public function __construct($conf)
    {

        $host = isset($conf->host) ? $conf->host : 'localhost';
        $user = isset($conf->user) ? $conf->user : 'root';
        $password = isset($conf->password) ? $conf->password : '';
        $db = isset($conf->db) ? $conf->db : 'test';
        $charset = isset($conf->charset) ? $conf->charset : 'utf8';

        try {
            parent::__construct($host, $user, $password, $db);
        } catch (Exception $e) {
            throw new Base_Exception($e, __CLASS__);
        }

        /* Setup charset */
        $this->query("SET NAMES " . $charset);

    }
}

Так же можно заюзать и без throw Для этого в блоке catch (Exception $e) можно написать например echo $e->getMessage();
Методы класса Exception можно посмотреть в документации по PHP
.
(\/)____o_O____(\/)
L!MP, доделаю в паблик выложу, пока там половина готова

вроде сделал как хотелось, на суд выкладываю

/*
--
-- Table structure for table `table`
--

CREATE TABLE IF NOT EXISTS `table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `pass` varchar(32) NOT NULL,
  `time` int(11) NOT NULL,
  `pid` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
*/

$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'myli';
$db_charset = 'utf-8';

class KoeMysql extends Mysqli {
public $stmt;
public $sql = false;
public $afr = false;

public function __construct($db_host, $db_user, $db_pass, $db_name, $db_charset) {
@parent::__construct($db_host, $db_user, $db_pass, $db_name);
@$this->set_charset($db_charset);
if ($this->connect_errno) 
die($this->connect_error); 
}

public function count_params() {
return $this->stmt ? $this->stmt->param_count : die('stmt not started');    
}

public function count_fields() {
return $this->stmt ? $this->stmt->field_count : die('stmt not started');    
}

public function is_fetch() {
if ($this->sql) {
return preg_match('/select/i', $this->sql) ? true : false;    
} else {
die('Query not execute');    
}   
}

public function sql($sql, $where = 1, $limit = 1, $placeholders = '') {

$this->sql = $sql;    
$this->sql .= $this->where($where) ? $this->where($where) : '';
$this->sql .= $this->limit($limit) ? $this->limit($limit) : '';

if (!$this->stmt = $this->prepare($this->sql)) {
die('error sql [' . $this->sql . ']');
}

if ($this->count_params() && $placeholders) {
if (!$this->placeholders($placeholders)) {
die('Placeholders failed');    
}
}

if (!$this->is_fetch()) {
$this->stmt->execute();
$this->stmt->close;
return $this->affected_rows == -1 ? false : $this->affected_rows;
} else {
$this->stmt->execute();
if (!$this->bindresult()) {
die('Bind result failed');    
} 
}

//
echo '-- SQL --';
echo '<br/>' . $this->sql . '<br/>';
echo '----';
//

return $this->fetchresult();
}

public function fetchresult() {
if (!$this->num_rows) {
$return = false;    
} 
if ($this->count_fields()==1) {
$res = $this->stmt->get_result();
$row = $res->fetch_row();
$return = $row[0];
} else {
$return = array();    
$res = $this->stmt->get_result();
while ($row = $res->fetch_object()) {
array_push($return, $row);
}
}
return $return;    
}

public function bindresult() {
$result = array();    
$binds = array();
$meta = $this->stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$binds[] = &$row[$field->name];
}
if (!call_user_func_array(array($this->stmt, 'bind_result'), &$binds)) {
die('Not bind result');     
}
return $this->stmt;    
}

public function placeholders($args) {
if (!is_array($args)) {
$args = array($args);    
}
 
$types = '';
$newarray = array();
   
for ($i=0;$i<sizeof($args);$i++) {
$types .= is_numeric($args[$i]) ? 'i' : ((is_double($args[$i]) || is_float($args[$i])) ? 'd' : 's');
$newarray[] = $args[$i];
}

$args = array();
$args[] = $types;
foreach ($newarray as $k => $v) {
$args[] = &$newarray[$k];
}

echo '<pre>'; print_r($args);

if (!call_user_func_array(array($this->stmt, 'bind_param'), &$args)) {
die('Not bind params');    
}
return $this->stmt;    
}

public function where($args) {
if (is_int($args)) {
return false;    
} else {
$newarray = array();
if (sizeof($args)>0) {
foreach ($args as $k => $v) {
$newarray[] = '`' . $k . '` = ' . (($v!='?') ? '"' . $v . '"' : $v);
}    
return ' WHERE ' . implode(' AND ', $newarray);
} else {
return false;    
}
} 
}

public function limit($args) {
if ($args==0) {
return false;    
}

$str = ' ';    
if (is_array($args) && sizeof($args)==2) {
$str .= 'LIMIT ' . implode(' ,', array_values($args));
} elseif (is_int($args)) {
$str .= 'LIMIT ' . $args;        
} else {
die('Number of arguments 1 (string) or 2 (array)');    
}   
return $str;
}

public function __destruct() {
@$this->stmt->close();    
@$this->close();
}

}  

//  tests //

$mysqli = new KoeMysql($db_host, $db_user, $db_pass, $db_name, $db_charset);

$sql = "insert into `table` (id, name, pass, time, pid) values (?, ?, ?, ?, ?)"; 
$array = array(NULL, 'test', 'qwerty', time(), 213);
$where = 1;
$limit = 0; // need insert 
$res = $mysqli->sql($sql, 1, 0, $array); // || $res = $mysqli->sql($sql, $where, $limit, $array);
echo '<br> -- result - Affected rows ' . $res . '<br/>';
echo '<hr noshade />';

$sql = "select * from `table`";
$res = $mysqli->sql($sql, 0, 0); // fetch all lines
echo '<pre>'; print_r($res);  
echo '<hr noshade />';

$sql = "select * from `table`";
$where = array('pid' => '?', 'name' => '?');
$array = array(214, 'test');   // args is array
$limit = array(0, 20); // or $limit = 2; is string      
$res = $mysqli->sql($sql, $where, $limit, $array);
echo '<pre>'; print_r($res);  
echo '<hr noshade />';

$sql = "select `name` from `table`";
$res = $mysqli->sql($sql);
echo '<br> -- result - ' . $res . '<br/>';  
echo '<hr noshade />';


$sql = "delete from `table` where `id`<?"; 
#$array = array(); test empty args
$array = 980; // args is string
$where = 1;
$limit = 0;
$res = $mysqli->sql($sql, 1, 0, $array); // || $res = $mysqli->sql($sql, $where, $limit, $array);
echo '<br> -- result - Affected rows ' . var_dump($res) . '<br/>';
echo '<hr noshade />';
.
(\/)____o_O____(\/)
и тишина, а хотелось бы критики
.
Koenig (21.09.2012/18:49)
и тишина, а хотелось бы критики
ну давай по критикуем: Что это и зачем?
.
(\/)____o_O____(\/)
L!MP, я по поводу класса
Всего: 383