Php class member array

Массив объектов внутри класса в PHP

Недавно я понял, что мой подход к проекту в настоящее время значительно улучшится с использованием более / более описательных объектов. Таким образом, я понял, что хочу, чтобы массив объектов был членом другого класса.

Редактирование: Я не знал, что такое мой вопрос. Мой вопрос таков: как у меня есть массив в классе LogFile, который содержит объекты типа Match?

В конце концов я хочу иметь возможность сделать что-то вроде:

$logFile = new LogFile(); $match = new Match(); $logFile->matches[$i]->owner = “Brian”; 

Как мне сделать то, что я описал? Другими словами, что мне нужно сделать в классе LogFile для создания массива, который содержит объекты типа Match ?

class LogFile < public $formattedMatches; public $pathToLog; public $matchCount; public $matches = array(); >class Match < public $owner; public $fileLocation; public $matchType; >$l = new LogFile(); $l->matches[0] = new Match(); 

Это дополнение к ответу Брэда или Сваткинса . Вы написали:

что мне нужно сделать в классе LogFile для создания массива, который содержит объекты типа Match?

Вы можете создать «массив», который может содержать объекты соответствия. Это довольно легко, простираясь от ArrayObject и только принимая объект определенного класса:

class Matches extends ArrayObject < public function offsetSet($name, $value) < if (!is_object($value) || !($value instanceof Match)) < throw new InvalidArgumentException(sprintf('Only objects of Match allowed.')); >parent::offsetSet($name, $value); > > 

Затем вы LogFile класс LogFile который соответствует классу LogFile :

class LogFile < public $formattedMatches; public $pathToLog; public $matchCount; public $matches; public function __construct() < $this->matches = new Matches(); > > 

В конструкторе вы его настроили, новые Matches «Массив». Применение:

$l = new LogFile(); $l->matches[] = new Match(); // works fine try < $l->matches[] = 'test'; // throws exception as that is a string not a Match > catch(Exception $e) < echo 'There was an error: ', $e->getMessage(); > 

Демо – Надеюсь, это полезно.

Просто создайте другую общедоступную переменную для совпадений. Затем вы можете инициализировать его как массив в методе конструктора .

PHP не строго типизирован – вы можете поместить все, что угодно, в любую переменную. Чтобы добавить к совпадениям, просто выполните $logFile->matches[] = new Match(); ,

Затем, когда вы хотите добавить в массив:

$matches[] = $match; // $match being object of type match 

Вы можете использовать объект SplObjectStorage поскольку он предназначен для хранения объектов.

Источник

PHP5. Two ways of declaring an array as a class member

I’d suggest doing this when declaring a class variable. A constructor can be overriden in extending classes, which might result in E_NOTICEs or even E_WARNINGs if any of your functions depend on this variable being an array (even an empty one)

If you are going to populate your array dynamically during initialization, do it in the constructor. If it contains fixed values, do it in the property declaration.

Trying to populate an array dynamically (e.g. by using the return value of a certain function or method) within the declaration results in a parse error:

// Function call is not valid hereprivate $paths = get_paths();

Performance is not a real concern here as each has its own use case.

In general, because I write mostly in other languages besides PHP, I like to declare my instance variables outside of the constructor. This let’s me look at the top of a class and get an idea for all properties and their access modifiers without having to read the code.

For example, I really don’t like methods like this

// . // whole bunch of code// . public function initialize() < $this->foo = array(); // some other code to add some stuff to foo>

Now, if I just look at the class, I can’t be sure there is a variable foo even available. If there is, I don’t know if I have access to it from anywhere outside the instance.

at the top of my class, I know that foo is an instance property, and that I can access it from elsewhere.

Источник

PHP5. Two ways of declaring an array as a class member

I’d suggest doing this when declaring a class variable. A constructor can be overriden in extending classes, which might result in E_NOTICEs or even E_WARNINGs if any of your functions depend on this variable being an array (even an empty one)

Read More

There are no performance implications. Stop obsessing over things that don’t matter — concentrate on performance problems that ARE there: measure first, optimize only the top offenders.

In general, because I write mostly in other languages besides PHP, I like to declare my instance variables outside of the constructor. This let’s me look at the top of a class and get an idea for all properties and their access modifiers without having to read the code.

For example, I really don’t like methods like this

// . // whole bunch of code // . public function initialize() < $this->foo = array(); // some other code to add some stuff to foo > 

Now, if I just look at the class, I can’t be sure there is a variable foo even available. If there is, I don’t know if I have access to it from anywhere outside the instance.

at the top of my class, I know that foo is an instance property, and that I can access it from elsewhere.

sberry 123885

If you are going to populate your array dynamically during initialization, do it in the constructor. If it contains fixed values, do it in the property declaration.

Trying to populate an array dynamically (e.g. by using the return value of a certain function or method) within the declaration results in a parse error:

// Function call is not valid here private $paths = get_paths(); 

Performance is not a real concern here as each has its own use case.

More Answer

  • How to compare two array values in PHP
  • Merge and Overwrite Two or More Multidimensional Array
  • trying to call an array from multiple functions in a class
  • Translating two dimensional associative jquery array to php array
  • How do I refer to a «this» class member in a function parameter?
  • how to get two values repeating to use as a class
  • PHP array in class generated in function
  • using two mySQL queries to create nested JSON array
  • Have a php class return array values and keep looping until end
  • converting a two dimensional javascript array to JSON
  • Invoking a function from a class member in PHP
  • PHP class with property which can be either an int or an array
  • PHP class function, which takes an array of arrays, returns error
  • in php5 what is the technical term for specifying class name before object variable in a function parameters
  • PHP — Concatenating array values into a new array, given two arrays with identical keys
  • two array in Foreach
  • How can I form two arrays to one array object?
  • php: two objects from the same class work independent of each other
  • search&replace array key using PHP and CakePHP Set Class
  • two dimensional array PHP PDO
  • creating watermark in pdf’s created with dompdf’s php5 class
  • Ordering a column in a two dimensional array
  • How to assign a member function to an array and call it
  • Getting value of an array inside two arrays
  • Create array out of two arrays
  • Codeigniter 4 error call to a member function paginate() on array
  • PHP: Is there a null safe operator to prevent «Undefined array key» warning when merging two arrays?
  • Using php class for storing and grouping data to each person in array using different IDs
  • Getting a single array containing div class names and their inner li class names using php dom xpath query
  • Sort array object if two key’s value number are equal then match to another key value pair
  • Array Loop in a Loop need two time foreach?
  • Multidimensional array causing error Fatal error: Default value for parameters with a class type hint can only be NULL in PHPunit 5.7 laravel 5.6
  • How to count array values based on two columns in PHP?
  • Two foreach use with a array
  • How to merge two multi-dimensional array by its keys?
  • PHP Multidimensional Array to Two Column HTML Table
  • combine two array and get new one
  • Transform every two array items into associative array pairs
  • search array in another two dimensional array
  • How to slice two dimensional array php
  • PHP union two array in one
  • PHP — how to add $key => $value to two dimensional associative array
  • Create array of start and end datetimes from two datetime variables
  • How can I use the array_map with callback function as a member of array element?
  • How would I sort an Array of Std Class Objects by specific listing order?
  • How to find value exist in two dimentional array

More answer with same ag

  • Magento: Set default store view for customer groups
  • Toggling Bootstrap modal from PHP trigger
  • How do I use XPath on an XML with imports?
  • Internet Explorer doesn’t work with JavaScript function based on php generated select option values
  • Best way to handle error messages on a live site
  • __autoload does not run?
  • php check whether user has checked in or not
  • How to select dropdown by inserting value in the text box
  • replacing an iframe formular with own formular
  • Laravel — Javascript — save all quantities and id’s in a multidimensional array
  • phpword insert bullet list in a table
  • Shared Session Between Two Subdomains in PHP
  • File into nested array in PHP
  • Dummy email address implementation in PHP (Laravel)
  • Logout code not executing at all. php
  • How can I get form data to php via jquery
  • How to remove last comma from output from a for loop
  • Get mutiple multiple rows value base on array id IN CAKE PHP
  • MP3 meta data over http response
  • How to redirect back to edit page from a called function?
  • json_decode for twitch api
  • Can (php 8) doctrine attributes be inherited?
  • Prevent spam from my form
  • C pointer equivalents on other languages
  • bootstrap handling a ajax form submission
  • PHP does not redirect to a page after login
  • Magento: how to retrieve product final price (taking in account catalog price rules etc) while out of frontend
  • php address request
  • Custom redirect path if Registration fails on Laravel 5.3
  • Symfony voter and multiples reasons
  • I can’t change PHP session id
  • Unable to alert the message by capturing the array value in php using javascript.
  • Facebook Events Display Order
  • php login form using where clause with session data
  • Comparing the contents of 2 arrays
  • PHP ORM with support for SQL Server 2005
  • scayt button doesn’t show up nor scayt functions work
  • PHP strtotime() different between (‘Wednesday’) and (‘next Wednesday’)
  • PEAR HTML Quickform — Default File Upload path
  • PHP/JS: Multi-dim PHP array as Javascript Function Parameter
  • Any way to ignore stdClass Object in xml file?
  • Hybrid demo not returning oauth request token
  • Kohana ORM — Incorrect table name
  • JSON format lost in PHP
  • How do I use PHP’s str_replace() to generate multiple form checkboxes from multiple strings?
  • Php Xml loop through addAttribute
  • Eclipse Symfony 2 environments not found
  • Find a string and create a variable with regex
  • Google API Client refresh OAuth2 token
  • MySQL Transaction VS Table Lock for User Registration

Источник

Читайте также:  Права доступа index php
Оцените статью