AKB Forums

Go Back   AKB Forums > Technical sections > Languages, Compilers and Interpreters > Web Development
Home Register Blogs FAQ Members List Calendar Downloads Arcade Mark Forums Read

Web Development Java/PHP/Perl/ASP and more

Troubles when posting message? Click here! :: Проблемы с отправлением сообщения? Нажмите сюда!

Reply
 
LinkBack Thread Tools Display Modes
Old Jul 2, 2007, 08:56   #1
Младенец
 
Join Date: Jun 2007
Location: Yerevan
Posts: 9
Rep Power: 0
Reputation: 10
PHP Class Define

Barev dzez hargeli forumi masnakicner, Programmerner!!!

Unem mi harc Class - eri veraberyal, shat shnorhakal klinem lselu xorhurdner, ognutyan kargov.

Unenq Class - class.php - um
############################
class.php

class user() {
var $usr;

function set_username ($name) {
$this->usr=$name;
} // end function

function get_username () {
return $this->usr;
} // end function

} // end class
#############################

unenq naev index.php, vortex haytararum enq object

index.php
#############################

require("class.php");
$u=new user();
$u->set_username ('Armen');
echo $u->get_username();

#############################

ays amen@ haskanali e... bayts inchpes kareli e ogtvel classi objectneric mek ayl php fileum, orinak patkeracnenq vor ays index.php fileum classi $usr object@ stanum e arjeq... bayts ayd arjeq@ mez petq e naev myus fileum.. asenq other.php - um.

Naxapes shnorhakalutyun!
kernel is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 09:24   #2
Авик
 
CyberJoe's Avatar
 
Join Date: Jul 2002
Location: Yerevan
Posts: 1,347
Rep Power: 7
Reputation: 19
Send a message via ICQ to CyberJoe
uxxaki $u-n pet-q e global popoxakan lini vor karanas myus fileum el gres
$u->get_username();
mi qich indz tvuma konkret chi dep@ nkaragrac. u class-i het henc bun kap chuni.

p.s
karoxa du uzum es et classic menak mek instance unenas? et depqum petqa ogtagorces singleton, byc indz tvuma stex ays depq@ chi
__________________
вот собственно все, что я хотел сказать.
CyberJoe is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 15:40   #3
Младенец
 
Join Date: Jun 2007
Location: Yerevan
Posts: 9
Rep Power: 0
Reputation: 10
hargeli CyberJoe shat shnorhakal em xorhrdi hamar

shat shnorhakal em xorhrdi ev ognutyam hamar...

Ban@ nranum e, vor indz petq e ayd classi arjeqner@ pahel amboxch sessiai jamanak, aysinqn erb usr popoxakan@ stanum e arjeq, apa shrjelov tarber ejerum, es karoxanak stanal ayd arjeq@ $u->get_user(); mijocov.

u mi nurb pah el ka

asenq unem config.php u $u=new user(); haytararum em config.php - um.
isk config.php bolor filerum require("config.php"); em anum.
inch anem config.php - um, erb $u=new user();araj script@ haskana vor $u arden haytararvats e?

Krknaki angam naxapes shnorhakalutyun!
kernel is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 15:43   #4
Младенец
 
Join Date: Jun 2007
Location: Yerevan
Posts: 9
Rep Power: 0
Reputation: 10
u ete kareli e, knkaragres inch e "singleton" @ ?
kernel is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 15:59   #5
Авик
 
CyberJoe's Avatar
 
Join Date: Jul 2002
Location: Yerevan
Posts: 1,347
Rep Power: 7
Reputation: 19
Send a message via ICQ to CyberJoe
ha.. pastoren kez henc singletona petq

singletoni masin nayir aystex: http://en.wikipedia.org/wiki/Singleton_pattern

isk ko uzac@ henc saya:

PHP Code:
class User {
  
// object instance
  
private static $instance;
  
  private static 
$name;
 
  private function 
__construct() {}
 
  private function 
__clone() {}
 
  public static function 
getInstance() {
    if (
self::$instance === null) {
      
self::$instance = new User();
    }
    return 
self::$instance;
  }
 
  public function 
getName() {
    return 
$this->name;
  }
  
  public function 
setName($name) {
    
$this->name $name;
  }  
}
 

User::getInstance()->setName('Benjamin Linus');

$name User::getInstance()->getName(); 
aysinqn kez el $u popoxakan petq chi, mish kanchum es
User::getInstance(), ev nuyn popoxakannes stanum amentexic
__________________
вот собственно все, что я хотел сказать.

Last edited by CyberJoe : Jul 3, 2007 at 11:17.
CyberJoe is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 16:17   #6
Дикообраз-безобраз
 
AvDav's Avatar
 
Join Date: Jul 2004
Location: У самого синего моря
Posts: 2,608
Rep Power: 5
Reputation: 82
Send a message via ICQ to AvDav
А если ему надо создать несколько экземпляров класса Юзер? Тогда синглтон тут не применим. Не понимаю в чем проблема, просто создаешь обьект в конфиг.пхп и пользуешь в других файлах, что не получается то?
__________________
Deutschland, Deutschland über alles
Über alles in der Welt,

Wenn es stets zu Schutz und Trutze
Brüderlich zusammenhält,

Von der Maas bis an die Memel,
Von der Etsch bis an den Belt.

AvDav is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 17:12   #7
Младенец
 
Join Date: Jun 2007
Location: Yerevan
Posts: 9
Rep Power: 0
Reputation: 10
CyberJoe jan, shat shnorhakal em...

AvDav;588549]А если ему надо создать несколько экземпляров класса Юзер? Тогда синглтон тут не применим. Не понимаю в чем проблема, просто создаешь обьект в конфиг.пхп и пользуешь в других файлах, что не получается то?[/quote]

skaju chto dorogoy AvDav! Tut takoe delo... skajem v konfig.php ya sozdayu $u = new user(); OK?
A v index.php $u->set_user('David'); OK?
i skajem na stronice index.php est link lala.php, pre perexode lala.php najatiem na ssilku, (bez get, i post) kak v filee lala.php mne poluchit $u->get_username();

esle ya v lala.php stavlyu require("config.php"); to pre kajdom require iz raznix fileov v config.php object $u obyavlyaetsa vse snova i snova, no mne on nujen lish pre pervoy obyavlenii. i eshcho obyavlenie i set funkcii klass u menya nezoviseni, toest iz raznix php fileov v site...

Blagodaryu za pomoshch!
kernel is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 17:58   #8
Дикообраз-безобраз
 
AvDav's Avatar
 
Join Date: Jul 2004
Location: У самого синего моря
Posts: 2,608
Rep Power: 5
Reputation: 82
Send a message via ICQ to AvDav
Обьект не создается снова и снова, у тебя просто напросто глобальная перменная которая один раз создается при первом require, дальше логику надо строить так чтоб получить то что надо, насколько я понял, ты хочешь вызвать get_username(), с ожидаемым ответом 'David'? Тогда очевидно, тот кусок кода который делает set, должен вызваться раньше, соответсвенно, в lala.php надо сделать require("index.php"); а не require("config.php");
__________________
Deutschland, Deutschland über alles
Über alles in der Welt,

Wenn es stets zu Schutz und Trutze
Brüderlich zusammenhält,

Von der Maas bis an die Memel,
Von der Etsch bis an den Belt.

AvDav is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 21:33   #9
Младенец
 
Join Date: Jun 2007
Location: Yerevan
Posts: 9
Rep Power: 0
Reputation: 10
Dorogoy AvDav! mojet bit ya slishkom mnogo osujdayu voprosi, zadannie mnoyu, ush izvenite menya za eto ...
No vopros takov -
1) yesle ya v lala.php stavlyu require("index.php"); a ne config.php, to lala.php kak budet znat' o tom, chto set_user() bil vizvan v index.php, a ne skajem v koko.php? vet' set_user() mojet
vizvacca v lyubom file - e.
2) a stoit li stavit require("index.php"); poskolku index.php yavlyaetsa polnim html fileom ? (ne schetaya to chto mojno prosto kusok set_user() stavit iz drugogo filea skajem set.php )
3) ti prav, ya xochu poluchit pre pomoshchi get_user() - 'David', odnako functsia set_user(), mojet vizvacca iz lyubogo filea v site - e!
4) pre obyavlenii vo vsex fileax "config.php" - v config.php $u = new user(); srobativaet construktor kotori presvaivaet nekotorix peremennix znachenie po umolchaniu. i uje v drugix
fileax peremennie poluchayut drugie znachenie pre pomoshchi set_xxx(); tolko vot - pre pervom shage skajem v index.php vso rabotaet normalno require("config.php"); kotori (konfog)
obyavlyaet $u a v uje v index.php rabotaet $u->set_user(); no pre perexode v lala.php, ile je v koko.php ya ne znayu kak poluchit $u. vet' esle ya v etix fileax stavlyu config.php, to v
confige $u snova opredelyaetsa, kak v pervi raz iz index.php... mojet est' kakoy to variant uznat' v config.php o tom chto $u uje obyavlen, i ne nado bolshe pisat' $u=new user(); vet' v
koko.php ya poluchayu $u s pustimi znacheniami.
Blagodaryu, i izvenite mne eshcho za ne gramotni russki yazik
kernel is offline   Reply With Quote Quote selected
Old Jul 2, 2007, 23:00   #10
Дикообраз-безобраз
 
AvDav's Avatar
 
Join Date: Jul 2004
Location: У самого синего моря
Posts: 2,608
Rep Power: 5
Reputation: 82
Send a message via ICQ to AvDav
Не знаю если честно почему такая проблема, у меня солидного опыта в ПХП нет, но я тут наверстал пример который нормально работает, можешь также попробовать require_once() который помещает код лишь один раз в отличии от require().
__________________
Deutschland, Deutschland über alles
Über alles in der Welt,

Wenn es stets zu Schutz und Trutze
Brüderlich zusammenhält,

Von der Maas bis an die Memel,
Von der Etsch bis an den Belt.

AvDav is offline   Reply With Quote Quote selected
Old Jul 3, 2007, 03:57   #11
Дошкольник
 
Join Date: Oct 2004
Location: Yerevan
Posts: 116
Rep Power: 4
Reputation: 12
Send a message via ICQ to Intel
Quote:
Originally Posted by kernel View Post
Barev dzez hargeli forumi masnakicner, Programmerner!!!

Unem mi harc Class - eri veraberyal, shat shnorhakal klinem lselu xorhurdner, ognutyan kargov.

Unenq Class - class.php - um
############################
class.php

class user() {
var $usr;

function set_username ($name) {
$this->usr=$name;
} // end function

function get_username () {
return $this->usr;
} // end function

} // end class
#############################

unenq naev index.php, vortex haytararum enq object

index.php
#############################

require("class.php");
$u=new user();
$u->set_username ('Armen');
echo $u->get_username();

#############################

ays amen@ haskanali e... bayts inchpes kareli e ogtvel classi objectneric mek ayl php fileum, orinak patkeracnenq vor ays index.php fileum classi $usr object@ stanum e arjeq... bayts ayd arjeq@ mez petq e naev myus fileum.. asenq other.php - um.

Naxapes shnorhakalutyun!
В PHP нет встроенного механизма для хранения об'ектов в сессии, ты должен сам выбрать/реализовать механизм сериализации и десериализации, ты должен поставить в соответствие SID и об'ект юзера, например можешь хранить его в DB, сериализавать в XML, или даже использовать serialize и забросить в сессию. Такой подход чаще используется в языках/технологиях более высокого уровня, например Java/.NET.

CyberJoe > Синглтон тут неприменим, время жизни твоего об'екта будет request, а нам нужно чтоб было session.

AvDav > Речь идет о другом. Проблема в том что, если каждый раз делать require(или require_once, без разницы), твой об'ект заново инициализируется, а нам надо чтоб он "сам знал" что хранит, без каких лобо set-ов.

kernel > Я правильно понял?
Intel is offline   Reply With Quote Quote selected
Old Jul 3, 2007, 11:09   #12
Авик
 
CyberJoe's Avatar
 
Join Date: Jul 2002
Location: Yerevan
Posts: 1,347
Rep Power: 7
Reputation: 19
Send a message via ICQ to CyberJoe
Talking

Intel > Он точно именно это хотел? Я из его написанного понял что он вообще хочет просто иметь один инстанс класса, и все.

Кстати, бацец
PHP Code:
<?php
class User {
  
// object instance
  
private static $instance;
  
  private static 
$name;

  private function 
__construct() {}

  private function 
__clone() {}

  public static function 
getInstance() {
    if (@isset(
$_SESSION['user_instance'])) {
        
self:$instance unserialize($_SESSION['user_instance');
    } else {
        
self:$instance = new User();
        
$_SESSION['user_instance'] = serialize(self:$instance);    
    }
    return 
self::$instance;
  }

  public function 
getName() {
    
self:$instance unserialize($_SESSION['user_instance');
    return 
$this->name;
  }
  
  public function 
setName($name) {
    
$this->name $name;
    
$_SESSION['user_instance'] = serialize(self::$instance);        
  }  
}


User::getInstance()->setName('Benjamin Linus');

$name User::getInstance()->getName(); 
?>
Intel зацени степень моей обкуренности:-)
__________________
вот собственно все, что я хотел сказать.

Last edited by CyberJoe : Jul 3, 2007 at 11:31.
CyberJoe is offline   Reply With Quote Quote selected
Old Jul 3, 2007, 11:41   #13
Дошкольник
 
Join Date: Oct 2004
Location: Yerevan
Posts: 116
Rep Power: 4
Reputation: 12
Send a message via ICQ to Intel
Меньше курить надо было, а где session_start(); ?
Intel is offline   Reply With Quote Quote selected
Old Jul 3, 2007, 11:47   #14
Авик
 
CyberJoe's Avatar
 
Join Date: Jul 2002
Location: Yerevan
Posts: 1,347
Rep Power: 7
Reputation: 19
Send a message via ICQ to CyberJoe
за кадром осталсо
__________________
вот собственно все, что я хотел сказать.
CyberJoe is offline   Reply With Quote Quote selected
Old Jul 3, 2007, 19:53   #15
Младенец
 
Join Date: Jun 2007
Location: Yerevan
Posts: 9
Rep Power: 0
Reputation: 10
Quote:
Originally Posted by Intel View Post
kernel > Я правильно понял?
Pravilno i Tochno!!!!
kernel is offline   Reply With Quote Quote selected
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
The C++ programmer's "wedding" ByTheWay Fun 2 Nov 12, 2006 07:31
PHP 4.4.0 Problem... Mesrop Languages, Compilers and Interpreters 24 Nov 9, 2005 09:37
Help!Help!help! Awful Unix 56 Sep 21, 2005 12:32
PHP against ASP acid Web Development 1 Aug 6, 2004 21:30
PHP remote vulnerabilities VX Software Security 0 Mar 4, 2002 19:20


All times are GMT. The time now is 21:05.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
This board was founded on September 29, 2001
Powered by Viper Internet

Affordable Web Hosting | ParevNet

Buy text link