Can anyone help me with php classes example. I have to make class "information" that has information about users: id, email, password, first name, last name, phone.
Also, class must have a method to print all the user data on the output.
It's really simple skeleton, because you didn't try anything, so just for you to have idea how it works...
class User
{
private $id;
private $email;
// ...
public function __construct($id, $email...)
{
$this->id = $id;
$this->email = $email;
// ...
}
public function printAll()
{
return $this->id . ' ' . $this->email;
}
}
I suggest you reading this: http://codular.com/introducing-php-classes and then come back with any questions.
Here is an example of a PHP class:
class DBIGenerator{
private $table;
private $name;
private $path;
public function __construct($table,$name='default_file.php',
$path='DEFAULTPATH/'){
$this->table=$table;
$this->name=$name;
$this->path=$path;
}
public function generate(){
// build class header
$str='<?php class '.$this->name.'{';
if(!$result=mysql_query('SHOW COLUMNS FROM '.$this->table)){
throw new Exception('Failed to run query');
}
// build data member declaration
if(mysql_num_rows($result)<1){
throw new Exception('Not available columns in table');
}
$methods='';
while($row=mysql_fetch_array($result,MYSQL_ASSOC)){
$str.='private $'.$row['Field'].'=\'\';';
$methods.='public function set'.$row['Field'].'($'.$row
['Field'].'){$this->'.$row['Field'].'=$'.$row
['Field'].';}';
$methods.='public function get'.$row['Field'].'(){return
$this->'.$row['Field'].';}';
// store field names in array
$fields[]=$row['Field'];
}
// build empty constructor
$str.='public function __construct(){}';
// build modifiers and accessors
$str.=$methods;
// build load() method
$str.='public function load(){$r=mysql_query("SELECT * FROM
'.$this->table.' WHERE id=\'$this->id\'");';
$str.='return mysql_fetch_array($r,MYSQL_ASSOC);}';
// build submit() method
$str.='public function submit(){mysql_query("INSERT INTO '.$this-
>table.' SET ';
foreach($fields as $field){
$str.=($field!='id')?$field.'=\'$this->'.$field.'\',':'';
}
$str.='");$this->id=mysql_insert_id();';
$str=preg_replace("/,\"/","\"",$str).'}';
// build update() method
$str.='public function update(){mysql_query("UPDATE '.$this-
>table.' SET ';
foreach($fields as $field){
$str.=($field!='id')?$field.'=\'$this->'.$field.'\',':'';
}
$str=preg_replace("/,$/","",$str);
$str.=' WHERE id=\'$this->id\'");}';
// build delete() method
$str.='public function delete(){mysql_query("DELETE FROM '.
$this->table.' WHERE id=\'$this->id\'");}';
$str.='}?>';
// open or create class file
if(!$fp=fopen($this->path.$this->name.'.php','w')){
throw new Exception('Failed to create class file');
}
// lock class file
if(!flock($fp,LOCK_EX)){
throw new Exception('Unable to lock class file');
}
// write class code to file
if(!fwrite($fp,$str)){
throw new Exception('Error writing to class file');
}
flock($fp,LOCK_UN);
fclose($fp);
// delete temporary variables
unset($fp,$str,$row,$fields,$field,$methods);
}
public function getObject(){
// check if class file exists
if(!file_exists($this->path.$this->name.'.php')){
throw new Exception('Failed to include class file');
}
require_once($this->path.$this->name.'.php');
// create data access object
return new $this->name;
}
}
Read more at http://www.devshed.com/c/a/PHP/Building-ObjectOriented-Database-Interfaces-in-PHP-Updating-the-Application-to-PHP-5/1/#Czocu1kMhhuTvg2e.99
Take a look at the snippet below as a basic way to implementing as expressed:
<?php
class information
{
public $id = 1;
public $email = "mail#mail.com";
public $pw = "A2D7DFEA88AC88"; //Don't forget, PW are usually hashed ;)
public function id() {
echo $this->id;
}
public function email() {
echo $this->email;
}
public function pw() {
echo $this->pw;
}
}
$test = new information();
$test->id;
?>
Related
I am trying to display an array of messages at the end of my PHP class. My message handler is working, but only if I "add_message" from within the main parent class and not if I call this function from within a child class. Sorry if this is vague but was not sure how to word the question.
TLDR; How can I add a message from within class Example?
MAIN PARENT CLASS
class Init {
public function __construct() {
$this->load_dependencies();
$this->add_messages();
$this->add_msg_from_instance();
}
private function load_dependencies() {
require_once ROOT . 'classes/class-messages.php';
require_once ROOT . 'classes/class-example.php';
}
public function add_messages() {
$this->messages = new Message_Handler();
$this->messages->add_message( 'hello world' );
}
// I Would like to add a message from within this instance....
public function add_msg_from_instance() {
$example = new Example();
$example->fire_instance();
}
public function run() {
$this->messages->display_messages();
}
}
MESSAGE HANDLER
class Message_Handler {
public function __construct() {
$this->messages = array();
}
public function add_message( $msg ) {
$this->messages = $this->add( $this->messages, $msg );
}
private function add( $messages, $msg ) {
$messages[] = $msg;
return $messages;
}
// Final Function - Should display array of all messages
public function display_messages() {
var_dump( $this->messages );
}
}
EXAMPLE CLASS
class Example {
public function fire_instance() {
$this->messages = new Message_Handler();
$this->messages->add_message( 'Hello Universe!' ); // This message is NOT being displayed...
}
}
Because you want to keep the messages around different object, you should pass the object or use a static variable.
I would use a static variable like so:
class Init {
public function __construct() {
$this->load_dependencies();
$this->add_messages();
$this->add_msg_from_instance();
}
private function load_dependencies() {
require_once ROOT . 'classes/class-messages.php';
require_once ROOT . 'classes/class-example.php';
}
public function add_messages() {
// renamed the message handler variable for clarity
$this->message_handler = new Message_Handler();
$this->message_handler->add_message( 'hello world' );
}
// I Would like to add a message from within this instance....
public function add_msg_from_instance() {
$example = new Example();
$example->fire_instance();
}
public function run() {
$this->message_handler->display_messages();
}
}
class Message_Handler {
// use a static var to remember the messages over all objects
public static $_messages = array();
// add message to static
public function add_message( $msg ) {
self::$_messages[] = $msg;
}
// Final Function - Should display array of all messages
public function display_messages() {
var_dump( self::$_messages );
}
}
class Example {
public function fire_instance() {
// new object, same static array
$message_handler = new Message_Handler();
$message_handler->add_message( 'Hello Universe!' );
}
}
// testing...
new Init();
new Init();
$init = new Init();
$init->add_msg_from_instance();
$init->add_msg_from_instance();
$init->add_msg_from_instance();
$init->run();
Although global variables might not be the best design decision, you have at least two approaches to achieve what you want:
Use singleton.
Nowadays it is considered anti-pattern, but it is the simplest way: make message handler a singleton:
class MessageHandler
{
private static $instance;
private $messages = [];
public static function instance(): self
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
}
public function addMessage($message): self
{
$this->messages[] = $message;
return $this;
}
public function messages(): array
{
return $this->messages;
}
}
Then instead of creating a new instance of MessageHandler access it via the static method MessageHandler::instance(). Here is a demo.
Use DI container to inject the same instance (that is created once and held in the container) into all instances that need to access it. This approach is more preferable, but harder to implement in the project where there is no DI container available in the first place.
so I have this JSON object, which I have converted into a PHP object, for example I can use $apiobject->Response->DataItems and get a response.
This is stored in a class called returnjsonObject with a public function called getJsonObject.
In the same file how can I populate another class using the data from this $apiobject into something like:
class Response
{
public $StatusCode;
}
Then how can I for example echo out $StatusCode
Here is part of my file:
class Response
{
public $StatusCode; //*I want this to equal $apiobject->Response->DataItems*
}
class returnjsonObject{
public function getJsonObject()
{
echo"<pre>";
$apiobject = json_decode($response);
var_dump($apiobject->Response->DataItems);
echo"<pre>";
}
I've heard of using $this but I have to admit I don't understand it.
tl;dr I need to use $apiobject to populate $StatusCode using $apiobject->Response->DataItems
Hope you understand my question :-)
You can use setter and getter
class Response{
public $StatusCode;
/**
......
*/
public function __construct($attributes = Array()){
// Apply provided attribute values
foreach($attributes as $field=>$value){
$this->$field = $value;
}
}
function __set($name,$value){
if(method_exists($this, $name)){
$this->$name($value);
}
else{
// Getter/Setter not defined so set as property of object
$this->$name = $value;
}
}
function __get($name){
if(method_exists($this, $name)){
return $this->$name();
}
elseif(property_exists($this,$name)){
return $this->$name;
}
return null;
}
}
$DataItems =$apiobject->DataItems;
$response = new Response($DataItems);
echo $response->StatusCode;
Code not tested though. Learn more here.
http://www.beaconfire-red.com/epic-stuff/better-getters-and-setters-php
I would first set all attributes in Response Class from $apiobject like this
<?php
class Response {
public $StatusCode;
/* more attributes
...
*/
public $Name
} //end of Response class
Then instantiate Response class and set attributes
$response = new Response();
$response->StatusCode =$apiobject->DataItems->StatusCode;
$response->Name=$apiobject->DataItems->Name;
/* Set all other properties
.......
*/
echo $respose->StatusCode; //output status code
Note: you use $this to make reference to a function or a property in the current class. i.e
Class Example {
public $name;
public function getThatName(){
return $this->name; //we make reference to property `$name`
}
}
$this can only be use in a Class or Object to reference a property or a function in itself.
You can not do this.
$example = new Example();
$this->name; //Wrong because you are not in `Example` class
My question is simple, but I can't seem to find any answer for it online. I will probably jump straight into the code:
class NewClas {
public $id;
public function __construct($id) {
$this->id = $id;
$this->checkVars();
}
public function checkVars() {
if (empty($this->id)) {
trigger_error('ID is a required parameter.');
} elseif ($this->id WAS USED IN A PREVIOUS OBJECT) {
trigger_error('ID "'.$this->id.'" was used already. Please insert a unique name.');
}
}
}
$object1 = new NewClass('id1');
$object2 = new NewClass('id2');
$object3 = new NewClass('id1'); // throws error, because id1 was already used
So - is it possible to check for uniqueness of a value of the property among all instances of the class? I am just getting started with OOP, so please go easy on me. :)
Also, I am aware of spl_object_hash but I would prefer work with IDs as readable strings, specified by a user.
Thanks in advance!
It is possible - if you'll store static registry of used id's. That's about:
class NewClass
{
public $id;
//here's your registry
protected static $registry = array();
public function __construct($id)
{
$this->id = $id;
$this->checkVars();
//if not failed, add to registry:
self::$registry[] = $id;
}
public function checkVars()
{
if (empty($this->id))
{
trigger_error('ID is a required parameter.');
}
//checking if it's already used:
elseif (in_array($this->id, self::$registry))
{
trigger_error('ID "'.$this->id.'" was used already. Please insert a unique name.');
}
}
}
You can check this demo
It won't throw any error. You are triggering the error using the trigger_error under the else block. That's the reason you are getting an error.
When you do this..
$object3 = new NewClass('id1');
The id1 is passed as the parameter to the constructor and it is set to the $id public variable. Now checkVars() is going to be called .. Here $this->id will not be empty, so it will go to the else block.
This is the right code actually..
<?php
class NewClass {
public $id;
public function __construct($id) {
$this->id = $id;
$this->checkVars();
}
public function checkVars() {
if (empty($this->id)) {
trigger_error('ID is a required parameter.');
} else {
// trigger_error('ID is already used.');
}
}
}
$object1 = new NewClass('id1');
$object2 = new NewClass('id2');
$object3 = new NewClass('id1');
This is the right answer from above answer:
But to respect SOLID OOP design principles I would recommend to make id private and use getters and setters to access it.
class NewClass
{
private $id;
//here's your registry
public static $registry = array(); //since is static you can make it public
public function __construct($id)
{
$this->id = $id;
$this->checkVars();
//if not failed, add to registry:
self::$registry[] = $id;
}
public function checkVars()
{
if (empty($this->id))
{
trigger_error('ID is a required parameter.');
}
//checking if it's already used:
else if (in_array($this->id, self::$registry))
{
trigger_error('ID "'.$this->id.'" was used already. Please insert a unique name.');
}
}
So i am new to oo php and i-m building a sample app for learning purpses , one thing i must do is load a language file according to some settings
The code, as you will discover below is divided between two classes , a settings class witch should load the language file and another class in this case "contact" witch should read the array in the language files and display the propper message.
this is the Settings class
the lang variable sets the default language it can take 2 values at the moment : ro- for romanian and en - for english ,
class Settings
{
static public $lang = 'ro';
static public $load;
static public function get_language()
{
if(self::$lang == 'ro')
{
self::$load = require 'ro.php';
}
elseif(self::$lang == 'en')
{
self::$load = require 'en.php';
}
return self::$load;
}
}
The second class :
class Contact extends Settings {
//proprietati
public $nume;
public $subiect;
public $mesaj;
public $dincs;
//comportament - metode
public function __construct()
{
//$this->dincs = 'Din construct';
parent::get_language();
}
public function write_file()
{
if(empty($this->nume))
{
return $mess['name_error'];
}
else
{
$fp = fopen('data.txt', 'w');
fwrite($fp, $this->nume.".".$this->subiect .".". $this->mesaj."|".$this->dincs ."|".parent::$load);
fclose($fp);
return $mess['file_written'];
}
}
}
A sample from the language file:
$mess = array ("name_error" => "You must insert your name",
"file_written" => "the file has been written",
);
I have looked up on google , and tried some other stuff and can't seem to get it to work , and that may be because i am approaching this problem incorectly.
Plese help.
`
class Settings
{
protected $language = 'ro';
protected $load;
public function setLanguage($language = 'ro')
{
$this->language = $language;
// file_get_contents()
$this->load = require($this->language . '.php');
}
public function getLanguage()
{
return $this->language;
}
}
class Contact extends Settings
{
protected $name;
protected $subject;
protected $message;
protected $dincs;
protected $settingsObject;
// set all the properties below...
public function setName($name)
{
$this->name = $name;
}
public function setSubject($subject)
{
$this->subject = $subject;
}
public function setMessage($message)
{
$this->message = $message;
}
public function setDincs($dincs)
{
$this->dincs = $dincs;
}
// get all the properties...
public function getName()
{
return $this->name;
}
// This function only accepts an instance of Settings as the parameter
public function setSettingsObject(Settings $settings)
{
$this->settingsObject = $settings;
}
public function writeContentsToFile()
{
// if there is nothing in name, throw a new exception
if (empty($this->name))
{
throw new Exception('name has not been set! Set name before calling '. __METHOD__);
}
else
{
// get the file
$fp = fopen('data.txt', 'w');
// formatted string
$contents = sprintf('%s . %s . %s | %s | %s', $this->name, $this->subject, $this->message, $this->dincs, $this->settingsObject->getLanguage());
// write to the file
fwrite($fp, $contents);
// close the handler
fclose($fp);
return ('File written! Contents written: ' . $contents);
}
}
}
// instantiate settings
$settings = new Settings();
$settings->setLanguage('en');
// instantiate contact and set the settings object
$contact = new Contact();
$contact->setName('Joe Smith'); // if this is not set, ::writeContentsToFile will throw an Exception
$contact->setSettingsObject($settings);
// try and catch the Exception that ::writeContentsToFile may throw
try
{
echo $contact->writeContentsToFile();
}
catch (Exception $exception)
{
var_dump($exception);
}
?>
`
self::$load = require 'en.php';
You assign here a return value from the file inclusion to self::$load; not the variable $mess you defined in your language file.
So, there are two ways now: return the array $mess (return $mess;) from the language file.
Or you can just write:
require 'en.php';
self::$load = $mess;
Little side note: I'd check in your Settings::getLanguage() method if (self::$load) and return then the self::$load variable instead of refetching the language fileā¦)
so I am new in the world of object oriented programming and I am currently facing this problem (everything is described in the code):
<?php
class MyClass {
// Nothing important here
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction({$this->className} $object){
// So, here I obligatorily want an $object of
// dynamic type/class "$this->className"
// but it don't works like this...
}
}
$object = new MyClass;
$another_object = new MyAnotherClass('MyClass');
$another_object->problematicFunction($object);
?>
Can anyone help me ?
Thanks, Maxime (from France : sorry for my english)
What you need is
public function problematicFunction($object) {
if ($object instanceof $this->className) {
// Do your stuff
} else {
throw new InvalidArgumentException("YOur error Message");
}
}
Try like this
class MyClass {
// Nothing important here
public function test(){
echo 'Test MyClass';
}
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction($object){
if($object instanceof $this->className)
{
$object->test();
}
}
}
$object = new MyClass;
$another_object = new MyAnotherClass('MyClass');
$another_object->problematicFunction($object);
That's called type hinting and what you want to do is just not supported.
If all those dynamic class names have something in common (e.g., they're different implementations for certain feature) you probably want to define a base (maybe abstract) class or an interface and use that common ancestor as type hint:
<?php
interface iDatabase{
public function __contruct($url, $username, $password);
public function execute($sql, $params);
public function close();
}
class MyClass implements iDatabase{
public function __contruct($url, $username, $password){
}
public function execute($sql, $params){
}
public function close(){
}
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction(iDatabase $object){
}
}
Otherwise, just move the check to within problematicFunction() body, as other answers explain.