12

i am beginner on php so now i try to learn object oriented i was goggling i got it some ideas but not clear concept.So i come there.Please any php guru give simple example of how to crate classes and how to call on other php page.

for example

i want two classes one is show name and second one is enter name.First class show name this name come from database and second class put name in database.

Index.php

<form action="checking.php" method="post">
      <input type="text" placeholder="Please enter name">
</form>
Affan Ahmad
  • 451
  • 4
  • 9
  • 22

2 Answers2

14

The way you are calling a php page is good. That is from HTML.

What I think, you are getting this wrong. A class showName to get name from database and enterName to save in database. Well what I suggest that should be a function within one single class.

<?php
class Name
{
    public $name;
    public function showName()
    {
        /**
        Put your database code here to extract from database.
        **/
        return($this->name);
    }
    public function enterName($TName)
    {
        $this->name = $TName;
        /**
        Put your database code here.
        **/
    }
}
?>

In checking.php you can include:

<?php
    include_once("name_class.php");
    $name = $_POST['name'];   //add name attribute to input tag in HTML
    $myName = new Name();
    $myName->enterName($name); //to save in database/
    $name=$myName->showName(); //to retrieve from database. 
?>

This way you can achieve this, this is just an overview. It is much more than that.

Veer Shrivastav
  • 5,434
  • 11
  • 53
  • 83
  • 1
    I think there's an error in your code. You can't put the `$` after a `$this->` because it will throw a PHP exception. See line `this->$name = $TName;` – RPDeshaies Oct 03 '14 at 15:34
4

You have to create a class person and two methods..

class Person{
    public $name;
        public function showName()
        {
             echo $this->name;
        }

        public function enterName()
        {
             //insert name into database
        }
}
Balaji Perumal
  • 830
  • 1
  • 6
  • 20
  • You should not "echo" from within a method. Just "return" and let the user of this class decide what he want to do with the given data. – Mischa Oct 09 '15 at 06:01
  • 3
    @MischaBehrend, return is good. But this method is not getName(). For getting/setting getter/setter will be good.. Anyway thanks for your interest in this answer after two years though. – Balaji Perumal Oct 13 '15 at 07:08