How to set value to variable of class and display it? - php

In my project, I have defined a Test class.
Only __construct function in this class, Here is code of Test class:
<?php
namespace model;
public class Test {
private $db;
protected $fields;
public $variables;
public function __construct($data = array()) {
if ($this->fields && $data) {
foreach ($data as $k => $d) {
if (!in_array($k, $this->fields)) {
unset($data[$k]);
}
}
}
$this->variables = $data;
}
}
Now I want to use this class, Here is my html code:
<body style="height:100%" >
<?php
include "o1ws1v/class/model/Test.php";//include class file
$test_model = new \model\Test();
$test_model->xie="zuo";
echo $test_model->xie;
?>
</body>
But unlucky, It works fail. Nothing is showed in console.
I have tested:
var_dump($test_model);
It also did nothing .
I want to assign value to a variable of Test class and display it.
Who can help me?

With your code as it is you'll get an error
PHP Parse error: syntax error, unexpected 'public' (T_PUBLIC),
expecting end of file in ...
Remove the public keyword from your Test class:
<?php
namespace model;
class Test {
private $db;
protected $fields;
public $variables;
public function __construct($data = array()) {
if ($this->fields && $data) {
foreach ($data as $k => $d) {
if (!in_array($k, $this->fields)) {
unset($data[$k]);
}
}
}
$this->variables = $data;
}
}

I think you have to change public class to only class and this portion of code should be working.
<?php
namespace model;
class Test {
private $db;
protected $fields;
public $variables;
public function __construct($data = array()) {
if ($this->fields && $data) {
foreach ($data as $k => $d) {
if (!in_array($k, $this->fields)) {
unset($data[$k]);
}
}
}
$this->variables = $data;
}
}

Related

Cannot use [] for reading when including

I have this PHP file:
<?php
namespace FrameWork\Controller;
abstract class ControllerBase
{
protected $action;
protected $vars;
public function __construct($action, $vars = NULL)
{
$this->action = $action;
$this->vars = $vars;
$this->populateVars();
}
public function run()
{
****BETWEEN HERE****
$r = new \ReflectionMethod($this, $this->action);
$params = $r->getParameters();
$funcParams[];
foreach($params as $param)
{
$paramName = $param->getName();
$funcParams[$paramName] = $this->vars[$paramName];
}
****AND HERE****
call_user_func_array(array($this, $this->action), $funcParams);
}
private function PopulateVars()
{
foreach($_GET as $key => $getVar)
{
$this->vars[$key] = $getVar;
}
foreach($_POST as $key => $postVar)
{
$this->vars[$key] = $postVar;
}
}
}
It is includeed in another file, and for some reason I am getting an exception thrown on the include.
Cannot use [] for reading
When I remove everything between ****BETWEEN HERE**** and ****AND HERE****, it works (or at least doesn't throw the same exception).
Any idea what's going on?
Have you tried replacing
$funcParams[];
with
$funcParams = array();
I think it will solve your problem.

PHP: Get Acces To Private Variable In Class

I've been doing a project in PHP for the last few hours and I have encountered into a problem.
The problem is I don't know how to access private variables in a class and I can't find it online.
Example:
<?php
class Example{
private $age;
public function __construct() {
$age = 14;
$this->checkAge();
}
private function checkAge() {
if($this->$age > 12)
echo "welcome!";
}
}
$boy = new Example();
?>
As far as I know, I should be able to access the variable with $this->$age but it isn't working.
Thank you.
EDIT: Got it working with help of the awesome stackoverflooooooooow community, this is how a working one looks.
<?php
class Example{
private $age;
public function __construct() {
$this->age = 14;
$this->checkAge();
}
private function checkAge() {
if($this->age > 12)
echo "welcome!";
}
}
$boy = new Example();
?>
Look at this approach.
first: create Entity that stores and retrieves data inside of private $attributes array, and with magic __set(), __get() You can also do like: $object->variable = 123
second: extend Entity with Human class and add some function specific to child class (for example hasValidAge()):
<?php
class Entity {
private $attributes;
public function __construct($attributes = []) {
$this->setAttributes($attributes);
}
public function setAttribute($key, $value) {
$this->attributes[$key] = $value;
return $this;
}
public function setAttributes($attributes = []) {
foreach($attributes AS $key => $value) {
$this->setAttribute($key, $value);
}
}
public function getAttribute($key, $fallback = null) {
return (isset($this->attributes[$key]))?
$this->attributes[$key] : $fallback;
}
public function __get($key) {
return $this->getAttribute($key);
}
public function __set($key, $value) {
$this->setAttribute($key, $value);
}
}
class Human extends Entity {
public function __construct($attributes = []) {
$this->setAttributes($attributes);
$this->checkAge();
}
public function hasValidAge() {
return ($this->getAttribute('age') > 12)? true : false;
}
}
$boy = new Human(['name' => 'Mark', 'age' => 14]);
if($boy->hasValidAge()) {
echo "Welcome ".$boy->name."!";
}
?>
p.s. I've removed echo "Welcome!" part from constructor because it's not cool to do echo from model object, in our example Human is model of Entity.

Creating staitic method and calling the method in PHP

I'm getting value form Form class by creating object.It's working fine.But I wanna do it using static method.I tried but did not succeed.
public function display()
{
$newform=new Form();
echo "<pre>";
var_dump($newform->getAll());
var_dump($newform->get('name'));
}
<?php
class Form
{
private $value = array();
function __construct() {
// here you can use some validation or escapes
foreach($_POST as $key=>$value)
$this->value[$key] = $value;
}
public function getAll() {
return $this->value;
}
public function get($value) {
$this->value = $_POST[$value];
return $this->value;
}
}
Maybe You should just try to read PHP documentation about static keyword?
Example:
class Form {
private static $value = array();
public static function factory() {
// here you can use some validation or escapes
foreach($_POST as $key => $value) {
static::$value[$key] = $value;
}
}
public static function getAll() {
return static::$value;
}
public static function get($key) {
return static::$value[$key];
}
}
Use:
public function display() {
Form::factory();
echo "<pre>";
var_dump(Form::getAll());
var_dump(Form::get('name'));
echo "</pre>";
}
you do not declare a function as public/private/protected outside of the class
you you want to call this method statically, you may try it
<?php
function display()
{
$newform=new Form($_POST);
echo "<pre>";
var_dump(Form::getAll());
var_dump(Form::get('name'));
}
class Form
{
private static $value = array();
function __construct(){
// here you can use some validation or escapes
function __constract($array){
foreach($array as $key=>$value)
self::$value[$key] = $value;
}
}
public static function getAll(){
return self::$value;
}
public static function get($value){
self::$value = self::$value[$value];
return self::$value;
}
}
Here is an example for getAll method. For get method the same idea:
public function display()
{
var_dump(Form::getAll());
}
class Form
{
private static $value = array();
public static function initPost()
{
foreach($_POST as $key=>$value)
self::$value[$key] = $value;
}
public static function getAll()
{
return self::$value;
}
}

using codeigniter PHP Fatal error: Class 'MY_Model' not found

Now I am learning CodeIgniter_2.1.4 but I got a php error;
I have a my_model.php file in /data/www/application/core
<?php
class MY_Model extends CI_Model {
const DB_TABLE = 'abstract';
const DB_TABLE_PK = 'abstract';
private function insert() {
$this->db->insert($this::DB_TABLE, $this);
$this->{$this::DB_TABLE_PK} = $this->db->insert_id();
}
private function update() {
$this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK);
}
public function populate($row) {
foreach($row as $key => $value) {
$this->$key = $value;
}
}
public function load($id) {
$query = $this->db->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $id,
));
$this->populate($query->row());
}
public function delete(){
$this->db->delete($this::DB_TABLE, array(
$this::DB_TABLE_PK => $this->{$this::DB_TABLE_PK},
));
unset($this->{$this::DB_TABLE_PK});
}
public function save(){
if(isset($this->{$this::DB_TABLE_PK})) {
$this->update();
}
else {
$this->insert();
}
}
public function get($limit = 0, $offset = 0) {
if($limit) {
$query = $this->db->get($this::DB_TABE, $limit, $offset);
}
else {
$query = $this->db->get($this::DB_TABLE);
}
$ret_val = array();
$class = get_class($this);
foreach ($query->result() as $row) {
$model = new $class;
$model->populate($row);
$ret_val[$row->{$this::DB_TABLE_PK}] = $model;
}
return $ret_val;
}
}
and my domain model is :
<?php
class Publication extends MY_Model {
const DB_TABLE = 'publications';
const DB_TABLE_PK = 'publication_id';
public $publication_id;
public $publication_name;
}
well when I get model in my controller I got this php error:
PHP Fatal error: Class 'MY_Model' not found in /data/www/application/models/publication.php on line 3
I have tried two hours finding the reason but failed ):
I have a my_model.php file in /data/www/application/core
the my_model.php should be renamed to MY_Model.php.
It should be a case-sensitivity issue. Class names must have the first letter capitalized with the rest of the name lowercase.
in your publications.php have the following statement before the class declaration.
require_once "my_model.php";
the error is because you haven't included the definition of My_Model in your publications.php

Find the property's scope within class

class ParentClass
{
public function list()
{
foreach ($this as $property => $value)
{
if (is_public($this->$property))
echo 'public: ';
else if (is_protected($this->$property))
echo 'protected: ';
echo "$property => $value" . PHP_EOL;
}
}
}
class ChildClass extends ParentClass
{
protected $Size = 4;
protected $Type = 4;
public $SubT = 1;
public $UVal = NULL;
}
$CC = new ChildClass;
$CC->list();
Using ReflectionProperty, it's possible. You could create a helper function if you want to make it less verbose:
<?php
function P($obj, $name)
{
return new ReflectionProperty($obj, $name);
}
class Foo
{
public $a;
public function __construct()
{
foreach (array_keys(get_object_vars($this)) as $name)
{
if (P($this, $name)->isPublic())
{
echo "Public\n";
}
}
}
}
new Foo();
?>

Categories