Programmation Orientée Objet avec PHP 5

La dernière version de PHP (version 5 ) offre davantage de possibilités pour la Programmation Orientée Objet (POO). Connaissant déjà cette méthode de programmation (avec d'autres langages tels JAVA ou C++), j'ai eu envie de m'y plonger et de voir ce que peut apporter la POO à un langage de programmation web (php dans mon cas). J'ai donc commencé à programmer quelques fonctionnalités en objet pour les 3 portails de Coconews  : Guadeloupe, Martinique et Guyane. J'ai utilisé la POO pour développer la zone privilège (bientôt en ligne) et le support par ticket.

poo

La POO est, comme son nom l'indique, basée sur la notion d'objet. Un objet possède des attributs (repésentant l'état de l'objet) et des méthodes (représentant des opérations applicables à l'objet). Toute la façon d'imaginer, de penser le code est remis en question par rapport au php classique (dit "procédural"). Il faut un petit temps d'adaptation pour faire du code réellement en objet. La difficulté provient du fait que l'on a parfois du mal à imaginer certaines notions virtuelles sous forme d'objet.

Ce qui est appelée "classe", est tout ce qui définit un objet. Un objet est unique (on parle ici d'instance ou d'occurence de classe) mais deux objets peuvent être instanciés à partir de la même classe. Donc la première chose à faire en POO, c'est de créer une classe (après avoir analyser le problème et savoir ce que l'on veut faire exactement. Voici sommairement la syntaxe à respecter pour créer une première classe (contenu du fichier MaClasse.class.php) :

class MaClasse {
	private $id;
	private $attribut;
	public function __construct($id= null, $attribut= null)
	{
		if(!empty($id)) {
			$this->id = $id;
		}
		if(!empty($attribut)) {
			$this->attribut = $attribut;
		}
	}

	public function affiche()
	{
		echo "L'attribut vaut $this->attribut";
	}
}

Quelques explications sur la classe créée ci-dessus :

  • Une des premières règles de la POO est que le nom de la classe doit commencer par une majuscule. Après avoir indiqué le nom de la classe, on définit les attributs de cette classe (ici les attributs sont id et attribut. La première fonction (__construct) est appelé le constructeur de la classe. C'est grâce à cette fonction que l'on peut créer un objet de cette classe en faisant simplement "new()" (voir ci-après).
  • La variable $this est une variable spécifique à la POO, elle permet d'indiquer que c'est cet objet qui est modifié. $this->id correspond à l'attribut id de l'objet sur lequel on travaille.
  • La deuxième fonction (affiche) est une méthode de l'objet, ici c'est une méthode toute simple qui permet d'afficher, avec une phrase, la valeur de l'attribut nommé attribut.

Une fois la classe créée, il faut pouvoir s'en servir et créer des objets de cette classe :

include("MaClasse.class.php");$objet = new MaClasse(1, 10);$objet->affiche();

La première ligne permet d'inclure le fichier contenant la classe. La deuxième instruction permet de créer un nouvel objet grâce à l'appel au constructeur avec le mot "new". Après cette ligne, on a donc un objet MaClasse (nommé "$objet") dont les attributs id et attribut ont respectivement 1 et 10 comme valeur. Enfin la dernière ligne affiche : "L'attribut vaut 10".

Voici donc le nécessaire pour débuter avec la POO en PHP. Malgré le temps d'adapation à la philosophie de la POO, cette technique de programmation fait gagner du temps. En effet, on se trouve, à la fin, avec un code plus compréhensible (surtout sur des gros projets), plus facilement réutilisable et surtout plus facilement maintenable.

Enfin, je mets quelques liens qui m'ont permis de débuter avec la Programmation Orientée Objet en PHP. Je préfère apprendre avec des exemples concrets, donc la plupart de ces liens vous en présenteront :

Commentaires

  • homepage
    If you want to get a grewat deal from this paragraph then you have to apply these strategies to your won web site.

    магазин чехлов для телефонов homepage кэшбэк сервисы
  • what is 3d architectural visualization
    I appreciate, cause I disfovered just what I used to be having a
    loook for. You have ended my four dayy long hunt! Good Bless you man. Have a
    great day. Bye
  • natural lip fillers London
    If you are going for besst contents like myself, simply go to see this
    web page alll the time since it presents feature contents, thanks
  • bosch battery mercedes benz
    Highly descriptive article, I enjoyed that bit. Willl
    there be a part 2?
  • development finance services
    Hi there, I discovered your blogg by the usse off Google whilst searching for a comparable subject, your web site came up, it seems to be good.
    I've bookmarked it inn my google bookmarks.
  • buy gun
    This capability may be set up to consider top quality screenshots and also forwards them to your
    bank account. This article looks at some of their more questionable activities.

    many of you may find this hard to believe, but this is a relatively new concept.
  • website
    Thanks designed for sharing such a nice opinion, post is good, thats why i have read it entirely
    website
  • find games
    Very good article. I definitely appreciate this website.
    Keep writing!
  • best London escape game
    There's certainly a lot to find out about this subject.

    I like all the points you made.
  • sri lankan models
    What's up, yup this paragraph is really nice and I have learned lot of things from it regarding
    blogging. thanks.
  • acquistare bitcoin con bonifico bancario
    Excellent, what a web site it is! This weblog provides helpful facts to us, keep it up.
  • motorbike battery cost
    [/BLOG]
  • آموزش کودک دوزبانه
    I pay a visit day-to-day some websites and blogs to read content, however
    this weblog offers feature based posts
  • Lensamovie
    Enjoy the Best Movie associated with All Time
    What video do you want in order to watch today? Sniper videos may be required about your list.
    This is usually the most fun shooting struggle, where every sniper action is
    always interesting to watch.
  • J lo's Net Worth
    Very good blog! Do you have any tips for aspiring writers?

    I'm planning to start my own website soon but I'm a little lost on everything.
    Would you propose starting with a free platform like Wordpress or
    go for a paid option? There are so many choices out there that
    I'm totally confused .. Any suggestions? Kudos!
  • Google smart door lock
    Nice weblog right here! Also your web site a lot up fast!
    Whaat web host are you the usage of? Can Iget your affiliate hyperlink on your host?
    I desiee my website loaded up as fast as yours lol
  • Jumping Castle Hire Singapore
    Thanks in favor of sharing such a pleasant opinion, article is nice, thats why
    i have read it fully
  • best commercial espresso machine small coffee shop
    Aw, this was an exceptionally good post. Findijg the time and actual effort
    to produce a grdat article... but what ccan I say... I
    put things off a lot and don't seem to get nearly anything done.
  • website
    Spot on wirh this write-up, Itruly feel this amazing site
    needs far more attention. I'll probably be returning to ssee more,
    thanks for the advice!
    танец живота киев website фитнес на троещине
  • Jump Manual
    I'm impressed, I must say. Seldom do I come across a blog that's bolth equally educative andd engaging, and without
    a doubt, you have hit the nail on the head. The issue is an issue that not enough filks
    are speaking intelligently about. Now i'm very happy that I stumbled
    across this in mmy hunt for something regarding this.
  • CST application
    I rattling delighted too find this site on bing, just what I was searching for :D likewie bookmarked.
  • Surgery virtual reality
    An interesfing discussion is worth comment.
    I think that you should puhlish more on this issue, it may not be a taboo subject but usually people
    do not speak bout such topics. To the next! Many thanks!!
  • marketing for online courses
    Your style is so unique in compardison to other folks I've
    read stuff from. I appreciate you for posting when you have the opportunity, Guess Iwill just book mazrk this web site.
  • Home
    • 24. Home Le Jeu 05 nov 2020
    I precisely had to appreciate you once more. I am not sure what I could possibly have tried without the basics rewvealed by you regarding my area
    of interest. It became a vedy distressing dilemma in my view, nevertheless
    witnessing the well-written fashion you managed it made me to
    jump over happiness. Now i'm happier for the informatin and as well , hope you find out what a
    powerful jobb that you are accommplishing educating people today thru a site.
    Most likey you hae never encountered any
    of us.
  • best place for car battery
    Good post. I learn something new and challenging on sites I stumbleupon every day.
    It's alwayts interesting to read articles from other authors and use something from
    other sites.
  • Bouncing Castle For Kids
    Wonderful post! We are linking to this particularly great content on our website.

    Keep up the good writing.
  • communication and productivity in the workplace
    I do not even understand howw I stopped up right here,
    however I thought thos put up used to bbe great. I don't recognise who you're however definitely you aare going to a well-known blogger when youu are not already ;) Cheers!
  • 근로장려금 신청자격 조건 방법
    This means having them help you to set-up accounts that accurately reflect the common and recurring income
    and expense items about your properties. - is quite challenging to detect because its usage of emotional
    and social triggers. (4) Hidden prices: Customers wish to have all with the information you need before they create
    a purchase.
  • Bouncy Castle Hire Singapore
    Wonderful goods from you, man. I have understand your stuff
    prior to and you are simply extremely excellent. I actually
    like what you have bought right here, really like what you are
    stating and the way in which wherein you assert it.
    You are making it enjoyable and you continue to take care of to keep it wise.

    I cant wait to read far more from you. This is actually a tremendous website.
  • product packaging labels Redditch
    Some genuinely superb info, Gladiola I noticed this.
  • Jumppy Pte ltd
    Hey! I know this is kinda off topic but I'd figured I'd ask.

    Would you be interested in trading links or maybe guest authoring
    a blog post or vice-versa? My blog goes over a
    lot of the same subjects as yours and I think we could greatly benefit from each other.
    If you're interested feel free to send me an e-mail.
    I look forward to hearing from you! Great blog by the
    way!
  • Ferienhaus Werder
    Awesome post.
  • 식당인테리어
    Sufficient proofs must be attached meant for the causes stated in the letter.
    The higher the borrower's debt, the more likely they may be to default on a poor credit mortgage.
    there are the commitments you earn to yourself---commitments to
    non-public success, what watch owner should do.
  • course booking system
    Excellent job over again! Thanks.
  • کودک دو زبانه
    I'm gone to inform my little brother, that he should also visit this web site
    on regular basis to take updated from newest
    news کودک دوزبانه .
  • como conquistar uma mulher
    Faço confiança todos o conceitos tem introduziu para seu
    postar. Eles são muito convincente e será certamente funcionar.
    Não obstante, os posts são muito rápida para iniciantes .
    Você poderia alongar-los um pouco de próxima
    tempo? Obrigado para o post.
  • JAV Mom
    For most up-to-date news you have to pay a quick
    visit web and on web Japansex Mom found this web site
    as a finest site for newest updates.
  • cleaning extractor filters Bracknell
    Excellent blog here! Also your web site so much up very fast!
    What host are you the use of? Can I get your associate link on your host?
    I desire my web site loaded up as quickly as yours lol.
  • Toyota battery car price
    Hello mates, itts wonderful article on the topic of educationand fully
    defined, keep itt up all the time.

Voir plus de commentaires

Ajouter un commentaire