initialise instances inside a class php - php

How do I initialize objects inside a function within a class? so I can call each object like page[0]->getTitle(); or page[1]->getDescription();
The error now says :
Fatal error: Using $this when not in object context in C:\xampp\htdocs\class.page.php on line 92
index.php
Page::createObjects();
and my page.class.php
private title;
private description;
private page;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public static function createObjects(){
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$this->page[$i] = new self("Title", "Description");
}
}

You might consider having two different classes here, Page (page.class.php) and Pages (pages.class.php). Your Page class will represent an individual page record from your database, and your Pages class will contain methods that work on a set of records.
page.class.php
<?php
class Page
private title;
private description;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public function getTitle()
{
return $this->title;
}
public function getDescription()
{
return $this->description();
}
}
?>
pages.class.php
<?php
class Pages
public static function createObjects(){
$pages = array();
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$pages[] = new Page("Title", "Description");
}
return $pages;
}
}
?>
Then in your index.php, you get your Page objects from Pages
index.php
<?php
$pages = Pages::createObjects();
// to get the title of the first object
echo $pages[0]->getTitle();
?>

Like others commented, you can't access $this from a static function
a static field/variable/property/method belong to the class, not to a specific instance
<?php
class VIP
{
private $name, $surname;
private static $vips = array();
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
self::$vips[] = $this;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
static function getAll(){
return self::$vips;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
echo $a->getCredentials() . "\n";
foreach(VIP::getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
demo: https://eval.in/161874
however, this is more than likely bad code, since you are a beginner you should forget of static fields and methods and just use regular ones
better code:
<?php
class VIP
{
private $name, $surname;
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
}
class VIPsList
{
private $storage = [];
function add(VIP $vip){
$this->storage[] = $vip;
}
function getAll(){
return $this->storage;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
$collection = new VIPsList();
$collection->add($a);
$collection->add($b);
$collection->add($c);
$collection->add($d);
echo $a->getCredentials() . "\n";
foreach($collection->getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
https://eval.in/161898

Related

Codeigniter cannot redeclare class

Not: Its work just one time in loop. Its return this error for other time.
I have a usermodel.php in models. When i use it like
$this->load->model("Usermodel");
$user = $this->Usermodel->quer(1);
it throw "Message: Undefined property: CI_Loader::$Usermodel"
When i use
$this->load->model("Usermodel");
$user = new Usermodel();
it throw "Message: Cannot redeclare class Users"
user class has construct and desturct functions. I call it in Usermodel.php file. And usermodel has construct and destruct functions.
<?php
class User {
public function __construct(){
parent::__construct();
}
private $id;
private $email;
private $name;
private $profilPic;
private $topPic;
private $gender;
private $birthday;
private function setid($id){
$this->id = $id;
}
private function getid(){
return $this->id;
}
private function setemail($email){
$this->email = $email;
}
private function getemail(){
return $this->email;
}
private function setname($name){
$this->name = $name;
}
private function getname(){
return $this->name;
}
private function setprofilPic($profilPic){
$this->profilPic = $profilPic;
}
private function getprofilPic(){
return $this->profilPic;
}
private function settopPic($topPic){
$this->topPic = $topPic;
}
private function gettopPic(){
return $this->topPic;
}
private function setgender($gender){
$this->gender = $gender;
}
private function getgender(){
return $this->gender;
}
private function setbirthday($birthday){
$this->birthday= $birthday;
}
private function getbirhday(){
return $this->birthday;
}
public function __set($name, $value){
$functionname = 'set'.$name;
return $this->$functionname($value);
}
public function __get($name){
$functionname = 'get'.$name;
return $this->$functionname();
}
public function __destruct(){}
}
?>
This is usermodel
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Usermodel extends CI_Model {
public function __construct(){
parent::__construct();
$this->load->view("Users.php");
$this->load->model("Dbmodel");
}
public function quer($id){
$uqcont = array("id" => $id);
$uiqcont = array("userID", $id);
$uq = $this->Dbmodel->control("user", $uqcont);
$uiq = $this->Dbmodel->control("userinfo", $uiqcont, $limit=1, 'userID');
$user = new Users();
if($uq->num_rows()==1){
$uq = $uq->result();
$user->id=$id;
$user->name=$uq[0]->name;
$user->email=$uq[0]->email;
$user->profilPic="girlprofil.png";
$user->topPic="arka.jpg";
}
if($uiq->num_rows()==1){
$uiq=$uiq->result();
if($uiq[0]->profilPic){
$user->profilPic = $uiq[0]->profilPic;
}
if($uiq[0]->topPic){
$user->topPic = $uiq[0]->topPic;
}
}
return $user;
}
public function __destruct(){}
}
?>
This is a part of my view.php
foreach($query->result() as $row){
$cont = array("id" => $row->userID);
$query = $this->Dbmodel->control("user", $cont);
$this->load->model("Usermodel");
$user = new Usermodel();
$user = $user->quer($row->userID);
$date = new datetime($row->date);
$date = $date->format("d.m.Y H:i:s");
//$query = $query->result();
//foreach($query as $qur){
echo '$user->name.'<br>'.$row->comment;
//}
//unset($user);
}
Please look to my error and help me to solve it.
the class User is being declared more than once, probably in the loop you were referring to.
is this line in the loop?
$this->load->model("Usermodel");
if so try moving it out of the loop.
The error is due to loading the model several times in the foreach loop. Load it only once then create instances of the class as many times as you wish
$this->load->model("usermodel");
foreach($query->result() as $row){
$cont = array("id" => $row->userID);
$query = $this->Dbmodel->control("user", $cont);
$user = new Usermodel();
$user = $user->quer($row->userID);
$date = new datetime($row->date);
$date = $date->format("d.m.Y H:i:s");
}
Then consider using small caps in your load->model().
I advise loading the data in the controller then passing the data to the view. Let the controller have most of the logic.For example in the controller
$this->load->model('usermodel');
$data['users'] = $this->usermodel->quer($id)->result();
$this->load->view('users_view', $data);
In the view its as simple as
foreach ($users as $user)
{
//logic e.g. echo $user->name;
}
$this->load->model("X") is doing something like following;
Check models directory if X.php exists and if it exists
it creates the class with the given name in our case "X", [ $this->X = new X(); ]
you can also pass the alternative name to the load->model method like
$this->load->model("X","my_x_model"), in that case the loader module will create
$this->my_x_model = new X();
It was just to give some information about "what happens when you trying to load a model"
You're getting an Undefined property because
$this->load->model("usermodel");
has to be in lowercase.
https://www.codeigniter.com/userguide3/general/models.html#loading-a-model
I change this "class Users" to "class users extends CI_Model" and i move "$this->load->model("usermodel") on over of loop. Then the problem is solved. Thank you for help.

how pass parameter to php class by class()::function()

How pass parameter to PHP class by class()::function()?
class greenHouse{
public function __construct(connection $con){
}
public function show(){
}
}
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();
works
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();
doesn't work
I want to pass a parameter to the class with $nameclass($con)::$namefunction();. How do I do that in PHP?
You are trying to call a function statically with that notation...
$nameclass = 'greenHouse';
$namefunction = 'show';
$class = new $nameclass($con);
$class->$namefunction();
You can instantiate an object and immediately discard it by calling new within braces:
class Test
{
private $name;
function __construct($name)
{
$this->name = $name;
}
function speak()
{
echo $this->name;
}
function __destruct()
{
echo 'dead';
}
}
$class='Test';
$method='speak';
(new $class('David'))->$method();
echo ' is ';
$temp = new $class('John');
$temp->$method();
echo ' is ';
//Daviddead is John is dead
So in your case:
(new $nameclass($con))->$namefunction();

Fatal error: Using $this when not in object context in C:\xampp\htdocs\kotekli-clup\oop\class\DB.php on line 32

I've got a big problem:
I'm writing a new WebApp without a Framework.
I'm using xampp and sublime text.
I dont know how can i solve this problem.
An example how my DB.php written
class DB{
private static $_baglan = null;
private $_pdo,
$_query,
$hatalar = false,
$sonuc,
$_sayac = 0;
public function __construct(){
try{
$this -> _pdo = new PDO('mysql:host=' . Config::getir('mysql/host') . ';dbname=' . Config::getir('mysql/db'), Config::getir('mysql/kullanici_adi'), Config::getir('mysql/sifre') );
// echo 'baglandi';
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function baglan(){
if (!isset(self::$_baglan)) {
self::$_baglan = new DB();
// echo 'baglandi';
}
return self::$_baglan;
}
public static function query($sql, $parametre=array()){
$this->_hatalar = false; // line 32
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($parametre)) {
foreach ($parametre as $param) {
$this->_query->bindValue($x, $parametre);
$x++;
}
}
if ($this->_query->execute()) {
$this->sonuc=$this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_sayac=$this->_query->rowCount();
}else{
$this->_hatalar=true;
}
}
return $this;
}
public function eylem($eylem, $tablo, $where=array()){
if (count($where)===3) {
$operatorler = array('=', '<', '>', '>=', '<=');
$alan = $where[0];
$operator = $where[1];
$deger = $where[2];
if (in_array($operator, $operatorler)) {
$sql = "{$eylem} FROM {$tablo} WHERE {$alan} {$operator} ?";
if (!$this->query($sql, array($deger))->hatalar()) {
return $this;
}
}
}
return false;
}
public function getir($tablo, $where){
return $this->eylem('SELECT *', $tablo, $where);
}
public function sil($tablo, $where){
return $this->eylem('DELETE', $tablo, $where);
}
public function hatalar(){
return $this->hatalar();
}
}
In my index.php I'm loading maybe
require_once 'core/init.php';
// echo Config::getir('mysql/host');
// calismadi $kullanici = DB::baglan() -> query("SELECT kullanici_adi FROM uye WHERE kullanici_adi = ?", array('oguzhan'));
$kullanici = DB::baglan()->getir('uye', array('kullanici_adi', '=', 'oguzhan'));
if ($kullanici->hatalar()) {
echo 'Kullanıcı yok';
}else{
echo 'Var';
}
Why is the error coming?
Your problem can be solved by removing the static keyword from the query method.
You can only use $this on instantiated objects. self or static references the class itself, not any instantiated objects of the class.
class Person{
private $name;
public function __construct(string $name){
$this->name = $name;
}
public function greet(){
echo 'Hello my name is ' . $this->name;
}
}
$person = new Person('Thomas');
$person->greet(); // prints 'Hello my name is Thomas'
$this works in this example because we first instantiated the object using the new keyword. We are also not using the static keyword on the of the methods and variables.
self and static act only on the class itself and not on the instantiated object. The difference between self and static is explained here.
Here is an example of self usage, notice the use of the static keyword on the methods and variables of the class:
class StaticClass{
private static $variable = '';
public static function change(string $variable){
self::$variable = $variable;
}
public static function print(){
echo self::$variable;
}
}
StaticClass::change('Hello');
StaticClass::print(); // print 'Hello'

Managing collection of items through adding/removing

I want have an in-memory data structure to be able to add or remove an item (in this instance a student) into some sort of table (just like a shopping cart) from the collection class I have created. At the moment, it just displays students. For instance, if I click add student, it will pop up below, and I can delete this student from below also.
How I could implement this?
Here is my Member.php class
<?php
class Member {
private $name;
private $age;
private $gender;
private $course;
public function __construct($name,$age, $gender, $course){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
$this->course = $course;
}
public function setName($name) { //Sets the age value
$this->name = $name;
}
public function setAge($age) { //Sets the age value
$this->age = $age;
}
public function setGender($gender) { //Sets the gender value
$this->gender = $gender;
}
public function setCourse ($course) {
$this->course = $course;
}
public function getName() { //Gets the name value
return $this->name;
}
public function getAge() { //Gets the age value
return $this->age;
}
public function getGender() { //Gets the gender value
return $this->gender;
}
public function getCourse() {
return $this->course;
}
}
?>
Here is my ObjectCollection.php
<?php
class ObjectCollection
{
//This is an array to hold line items
private $items_array ;
private $itemCounter; //Count the number of items
public function __construct() {
//Create an array object to hold line items
$this->items_array = array();
$this->itemCounter=0;
}
public function getItemCount(){
return $this->itemCounter;
}
public function addItem($item) {
$this->itemCounter++;
$this->items_array[] = $item;
}
public function getItem($index) {
return $this->items_array[$index];
}
}
?>
And finally displaying this through testcollection.php
<?php
$ObjColl = new ObjectCollection();
$member1 = new Member("Jessica Davidson", 21, "Female", "Computing");
$ObjColl->addItem($member1);
$member2 = new Member("Lucy Barnes", 22, "Female", "History");
$ObjColl->addItem($member2);
$member3 = new Member("Mark Smith", 24, "Male", "Social Science");
$ObjColl->addItem($member3);
for($i = 0;$i < $ObjColl->getItemCount();$i++){
$item = $ObjColl->getItem($i);
if ($item instanceof Member) {
print "<br> University Member: ";
}
print "Name: " . $item->getName();
print ". Age: " . $item->getAge();
print ". Gender: " . $item->getGender();
print ". Enrolled on: " .$item->getCourse() . " course<br>";
}
?>
At first if your ObjectCollection must collect only objects of Member class, use parameter type declaration. It’s good practice in OOP.
public function addItem(Member $item)
At second if you want work with ObjectCollection like with array, implement ArrayAccess and Iterator interfaces.
Example
<?php
class Member{
private $__name;
public function __construct($name){
$this->__name = $name;
}
public function getName(){
return $this->__name;
}
}
class MemberCollection implements ArrayAccess, Iterator{
private $__Collection = [];
private $__position = 0;
public function __construct(){
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->__Collection[] = $value;
} else {
$this->__Collection[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->__Collection[$offset]);
}
public function offsetUnset($offset) {
unset($this->__Collection[$offset]);
}
public function offsetGet($offset) {
return isset($this->__Collection[$offset]) ? $this->__Collection[$offset] : null;
}
function rewind() {
$this->__position = 0;
}
function current() {
return $this->__Collection[$this->__position];
}
function key() {
return $this->__position;
}
function next() {
++$this->__position;
}
function valid() {
return isset($this->__Collection[$this->__position]);
}
public function addItem(Member $Member){
$this->offsetSet(null, $Member);
}
}
$MC = new MemberCollection();
$Member1 = new Member('Name 1');
$Member2 = new Member('Name 2');
$MC->addItem($Member1);
$MC->addItem($Member2);
foreach ($MC as $Member){
echo '<br>' . $MC->key() . ':<br>';
var_dump($Member->getName());
}
unset($MC[0]); //Delete member from collection
?>

PHP - Using classes to fetch user info

Assume the connection to the database and all references to tables and cells is correct... how could I get something like this working?
class User
{
private $_display;
private $_email;
public function __construct($username)
{
$fetch_user = mysql_query("SELECT * FROM `registered_users` WHERE `user_name`='$username'");
$fetch_user = mysql_fetch_array($fetch_user);
$this->_display = $fetch_user['user_display'];
$this->_email = $fetch_user['user_email'];
}
}
$person1 = new User('username');
echo "Information: " . print_r($person1, TRUE);
the problem is it returns nothing. Doesn't thrown an error or anything when debugged. Is it viable method though? :S
Here is roughly what I would do:
<?php
class User{
private $username;
private $data;
public function __construct($username){
$this->username = $username;
if($this->valid_username()){
$this->load();
}
}
private function load(){
// Let's pretend you have a global $db object.
global $db;
$this->data = $db->query('SELECT * FROM registered_users WHERE user_name=:username', array(':username'=>$this->username))->execute()->fetchAll();
}
public function save(){
// Save $this->data here.
}
/**
* PHP Magic Getter
*/
public function __get($var){
return $this->data[$var];
}
/**
* PHP Magic Setter
*/
public function __set($var, $val){
$this->data[$var] = $val;
}
private function valid_username(){
//check $this->username for validness.
}
// This lets you use the object as a string.
public function __toString(){
return $this->data['user_name'];
}
}
How to use:
<?php
$user = new User('donutdan');
echo $user->name; //will echo 'dan'
$user->name = 'bob';
$user->save(); // will save 'bob' to the database

Categories