php 面向对象的php类简单例子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20603992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object oriented php class simple example
提问by Affan Ahmad
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.
我是 php 的初学者,所以现在我尝试学习面向对象,我一直在思考,我得到了一些想法,但没有明确的概念。所以我来了。请任何 php 大师举一个简单的例子,说明如何创建类以及如何调用其他 php页。
for example
例如
i want two classes one is show nameand second one is enter name.First class show name this name come from database and second class put name in database.
我想要两个类,一个是show name,第二个是enter name。第一个类显示名称,这个名称来自数据库,第二个类将名称放入数据库中。
Index.php
索引.php
<form action="checking.php" method="post">
<input type="text" placeholder="Please enter name">
</form>
回答by Veer Shrivastav
The way you are calling a php page is good. That is from HTML.
您调用 php 页面的方式很好。那是来自 HTML。
What I think, you are getting this wrong. A class showNameto get name from database and enterNameto save in database. Well what I suggest that should be a function within one single class.
我的想法是,你弄错了。一个类showName从数据库中获取名称和enterName数据库保存。好吧,我建议它应该是一个类中的一个函数。
<?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.phpyou can include:
在checking.php你可以包括:
<?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.
这样您就可以实现这一点,这只是一个概述。远不止这些。
回答by Balaji Perumal
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
}
}

